100. 岛屿的最大面积
本文最后更新于585 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com

https://www.programmercarl.com/kamacoder/0100.%E5%B2%9B%E5%B1%BF%E7%9A%84%E6%9C%80%E5%A4%A7%E9%9D%A2%E7%A7%AF.html

1.本题就是上两个题的小扩充版,要求岛屿总面积,在我没看代码之前,我就想着用dfs取一个全局变量用于计数,我认为一次dfs搜索到一个陆地就计数加一,看了代码才知道,对我我使用的这种方法,在主函数里就将第一块陆地记为1然后然后进入dfs去找到未经过的陆地然后置为true然后计数sum++然后在主函数最后res = max(res, sum)。本题我使用的就是dfs 然后看代码里的bfs思路其实也大差不差,还是队列然后轮空队列。tips:当这个条件if(!visited[nextx][nexty] && grid[nextx][nexty] == 1)像我下面代码写的时候就在主函数里sum = 1,而将这个代码放在终止条件处,就是单独拿出来一个条件的时候,sum = 0这样将所有计数的操作都交给dfs即可。

CPP

#include<bits/stdc++.h>
using namespace std;
int sum;
int dir[4][2] = {0,1,1,0,-1,0,0,-1};
void dfs(const vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y){
    
    for(int i = 0; i < 4; i++){
        
        int nextx = x + dir[i][0];
        int nexty = y + dir[i][1];
        if(nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size())continue;
        if(!visited[nextx][nexty] && grid[nextx][nexty] == 1){
            visited[nextx][nexty] = true;
            sum++;
            dfs(grid, visited, nextx, nexty);
        }
        
    }
    
}
int main(){
    
    int n, m;
    cin >> n >> m;
    
    vector<vector<int>> grid(n, vector<int>(m, 0));
    
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cin >> grid[i][j];
        }
    }
    
    vector<vector<bool>> visited(n, vector<bool>(m, false));
    int res = 0;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            if(!visited[i][j] && grid[i][j] == 1){
                sum = 1;
                visited[i][j] = true;
                dfs(grid, visited, i, j);
                res = max(res, sum);
            }
        }
    }
    
    cout << res <<endl;
}
文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇
Cream_dpl