题解 | 岛屿数量

岛屿数量

https://www.nowcoder.com/practice/5225a111760b46c2be897d97b4d8561f

#include <iostream>
#include <vector>

using namespace std;

const int N = 110;
char g[N][N];
bool st[N][N];

int dx[8] = {0,0,-1,-1,-1,1,1,1};
int dy[8] = {1,-1,0,-1,1,-1,0,1};
int n,m;

void dfs(int x,int y){
    st[x][y] = true;
    for(int i = 0;i < 8;i++){
        int nx = x + dx[i];
        int ny = y + dy[i];
        if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && !st[nx][ny] && g[nx][ny] == 'W'){
            st[nx][ny] = true;
            dfs(nx,ny);
        }
    }
    
}
int main() {

    cin>>n>>m;
    vector<pair<int,int>> key;
    for(int i = 1;i <= n;i++){
        for(int j = 1;j <= m;j++){
            cin>>g[i][j];
            if(g[i][j] == 'W'){
                key.push_back({i,j});
            }
        }
    }
    int cnt = 0;
    for(const auto& t : key){
        if(!st[t.first][t.second]){
            cnt++;
            dfs(t.first,t.second);
        } 
    }
    cout<<cnt;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 评论 收藏
分享
01-19 15:14
已编辑
延安大学 C++
累死的一条狗:我说白了这种玩意你直接点举报就完事了在给他挂出来
找工作以来,你最看不惯_...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务