中文概要:
输入m行n列的字符矩阵,统计字符@组成多少个八连块,如果两个字符所在的各自相邻(横竖对角),就属于同一个八连块
例如:
* * * * @
* @@ * @
* @ * * @
@@@ * @
@@ * * @
#include <iostream>
#include<algorithm>
#include<string.h>
using namespace std;
#define MAX 105
char d[MAX][MAX];
int a[MAX][MAX];
int n, m;
void dfs(int r, int c,int cnt)
{
if (r < 0 || r >= m || c<0 || c>=n)
return;
if (a[r][c] >0 || d[r][c] != '@')
return;
a[r][c] = cnt;
for (int dr = -1; dr <= 1; dr++)
for (int dc = -1; dc <= 1; dc++)
if (dr != 0 || dc != 0)
dfs(r + dr, c + dc, cnt);
}
int main()
{
while (scanf("%d%d",&m,&n)==2 && n && m) {
for (int i = 0; i < m; i++)
scanf("%s", d[i]);
memset(a, 0, sizeof(a));
int cnt = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (a[i][j] == 0 && d[i][j] == '@')
dfs(i, j, ++cnt);
printf("%d\n", cnt);
}
return 0;
}
感想:
妈的数组定义的i必须从0开始,我这个跟原来一样从1开始会出错,挑了半天没看出来