题目链接:http://cogs.pro:8081/cogs/problem/problem.php?pid=vxSmxkeqa
【题目描述】
输入一个n×n的黑白图像(1表示黑色,0表示白色),任务是统计其中八连块的个数。如果两个黑格子有公共边或者公共顶点,就说它们属于同一个八连块。如下图所示的图形有3个八连块。

【输入格式】
第1行输入一个正整数n(n≤700),此后输入n行,每行是由n个0或1组成的字符串。
【输出格式】
在此键入。
【样例输入】
6
100100
001010
000000
110000
111000
010100
【样例输出】
3
思路:以二维int数组存入整张图,设置vis数组表示当前位置是否访问过,读入时一定要以%1d读入,
因为一次只读一个,算法开始时将数组初始化为0,之后二层for循环遍历每个位置,如果vis为0且数据为1,
则进入dfs函数,每次访问将vis[i][j]赋值为1,搜索完ans++,最后结束循环。
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 #include <cstdio> 4 #include <string> 5 #include <cstring> 6 #include <algorithm> 7 using namespace std; 8 9 int N; 10 int ans = 0; 11 int c[1000][1000] = { 0 }; 12 int vis[1000][1000] = { 0 }; 13 int X[8] = { 1, 0, -1, 0, 1, -1, 1, -1}; 14 int Y[8] = { 0, 1, 0, -1, -1, 1, 1, -1}; 15 16 void dfs(int x, int y) 17 { 18 if (!c[x][y] || vis[x][y]) 19 return; 20 vis[x][y] = 1; 21 for (int i = 0; i < 8; i++) 22 { 23 int dx = x + X[i], dy = y + Y[i]; 24 dfs(dx, dy); 25 } 26 } 27 28 int main() 29 { 30 freopen("common.in", "r", stdin); 31 freopen("common.out", "w", stdout); 32 memset(c, 0, sizeof(c)); 33 memset(vis, 0, sizeof(vis)); 34 scanf("%d", &N); 35 getchar(); 36 for (int i = 1; i <= N; i++) 37 { 38 for (int j = 1; j <= N; j++) 39 { 40 scanf("%1d", &c[i][j]); 41 } 42 getchar(); 43 } 44 45 for (int i = 1; i <= N; i++) 46 { 47 for (int j = 1; j <= N; j++) 48 { 49 if (!vis[i][j] && c[i][j]) 50 { 51 ans++; 52 dfs(i, j); 53 } 54 } 55 } 56 printf("%d\n", ans); 57 return 0; 58 }
浙公网安备 33010602011771号