洛谷 P1141 01迷宫(dfs)

https://www.luogu.org/problem/P1141

思路:找到每一个连通块,不同连通块的标记不同,给标记赋值成该连通块的数量

 1 // luogu-judger-enable-o2
 2 #include <cstdio>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <cmath>
 6 #include <queue>
 7 #include <vector>
 8 #include <cstring>
 9 #include <map>
10 #define mem(a) memset(a,0,sizeof(a))
11 using namespace std;
12 typedef long long ll;
13 const int maxn = 200005;
14 const ll INF = 0x3f3f3f3f3f;
15 int dir[8][2]= {2,1,1,2,-2,1,-1,2,2,-1,1,-2,-2,-1,-1,-2};
16 int dir2[4][2]= {0,1,0,-1,1,0,-1,0};
17 bool flag;
18 int vis[1005][1005],sum[1000005];
19 int n,m,countt,num;
20 string s[1005];
21 void dfs(int x,int y){
22     countt++;
23     vis[x][y] = num;
24     for(int i = 0; i < 4; i++){
25         int fx = x + dir2[i][0],fy = y + dir2[i][1];
26         if(fx >=0 && fx < n && fy >=0 && fy < n && !vis[fx][fy] && s[x][y] == '0' && s[fx][fy] == '1')
27             dfs(fx,fy);
28         if(fx >=0 && fx < n && fy >=0 && fy < n && !vis[fx][fy] && s[x][y] == '1' && s[fx][fy] == '0')
29             dfs(fx,fy);
30     }
31 }
32 int main()
33 {
34 
35     while(cin >> n >> m){
36         mem(vis);
37         mem(sum);
38         num = 1;
39         for(int i = 0; i < n; i++)
40             cin >> s[i];
41         for(int i = 0; i < n; i++){
42             for(int j = 0; j < n; j++){
43                 if(vis[i][j] == 0)
44                 {
45                     countt = 0;
46                     vis[i][j] = num;
47                     dfs(i,j);
48                     sum[num] = countt;
49                     //cout << sum[num] << endl;
50                     num++;
51                 }
52             }
53         }
54         int x, y;
55         //for(int i = 1; i < num; i++) cout << sum[i] << endl;
56         for(int i = 0; i < m; i++){
57             cin >> x >> y;
58             cout << sum[vis[x-1][y-1]] << endl;
59         }
60     }
61     return 0;
62 }

 

转载于:https://www.cnblogs.com/LLLAIH/p/11294057.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值