洛谷P1451

背景:复习
简单的dfs,也可以说是有点像连通块

#include<iostream>
#include<utility>
using namespace std;
typedef long long ll;
#define fi(i,a,b) for(int i = a; i <= b; ++i)
#define fr(i,a,b) for(int i = a; i >= b; --i)
#define x first
#define y second
#define sz(x) ((int)(x).size())
#define pb push_back
using pii = pair<int,int>;
//#define DEBUG
char cell[105][105];
bool vis[105][105];
int n,m;
int ans;
void dfs(int x,int y){
    if(x < 1 || x > n) //说明x不合要求
        return;
    if(y < 1 || y > m) //说明y不合要求
        return;
    if(cell[x][y] == '0' || vis[x][y]) 
        return;
    //说明一定在这个矩阵中并且没有访问过这个细胞
    // cout << cell[x][y];
    vis[x][y] = true;
    dfs(x-1,y);
    dfs(x+1,y);
    dfs(x,y+1);
    dfs(x,y-1);
    //向4个方向搜索
}   
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n >> m;
    fi(i,1,n) fi(j,1,m) cin >> cell[i][j];
    // fi(i,1,n) fi(j,1,m) cout << cell[i][j] << " ";
    // cout << endl;
    fi(i,1,n) fi(j,1,m) 
    {
        if(cell[i][j] != '0' && !vis[i][j]){
            ans++;
            dfs(i,j);
        }
    }
    cout << ans << endl;
#ifdef DEBUG
    //freopen(D:\in.txt,r,stdin);
#endif
    return 0;
}
posted @ 2022-01-27 11:04  Sun-Wind  阅读(54)  评论(0编辑  收藏  举报