孤岛的总面积-卡玛

题目链接:孤岛的总面积
本题需要求的是孤岛的面积,孤岛是那些位于矩阵内部、所有单元格都不接触边缘的岛屿。
那么如果一个岛屿不是孤岛,那么其在搜索时,一定会产生越界,利用一个标记位来对越界进行标记,如果产生越界就不统计这个岛的面积。

#include <bits/stdc++.h>
using namespace std;

int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};

int num;

void dfs(vector<vector<int>>& graph, vector<vector<bool>>& visited, int x, int y, int& flag){
    for(int i = 0; i < 4; i++){
        int nextx = x + dir[i][0];
        int nexty = y + dir[i][1];
        if(nextx < 0 || nextx >= graph.size() || nexty < 0 || nexty >= graph[0].size()){
            flag = 1;
            continue;
        }else{
            if(graph[nextx][nexty] == 1 && !visited[nextx][nexty]){
                visited[nextx][nexty] = true;
                num++;
                dfs(graph, visited, nextx, nexty, flag);
            }
        }
    }
}

void bfs(vector<vector<int>>& graph, vector<vector<bool>>& visited, int x, int y, int& flag){
    queue<pair<int, int>> que;
    que.push({x, y});
    while(!que.empty()){
        pair<int, int> cur = que.front();
        que.pop();
        for(int i = 0; i < 4; i++){
            int nextx = cur.first + dir[i][0];
            int nexty = cur.second + dir[i][1];
            if(nextx < 0 || nextx >= graph.size() || nexty < 0 || nexty >= graph[0].size()){
                flag = 1;
                continue;
            }else{
                if(graph[nextx][nexty] == 1 && !visited[nextx][nexty]){
                    visited[nextx][nexty] = true;
                    num++;
                    que.push({nextx, nexty});
                }
            }
        }
    }
}

int main(){
    int n,m;
    cin >> n >> m;
    vector<vector<int>> graph(n, vector<int>(m));
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cin >>graph[i][j];
        }
    }
    int ans = 0;
    vector<vector<bool>> visited(n, vector<bool>(m, false));
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            if(graph[i][j] == 1 && !visited[i][j]){
                num = 1;
                visited[i][j] = true;
                int flag = 0;
                //dfs(graph, visited, i, j, flag);
                bfs(graph, visited, i, j, flag);
                if(flag == 0){
                    ans += num;
                }
            }
        }
    }
    cout << ans << endl;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值