題意:一個m*n的地圖,其中的格子要麼是*,要麼是@,對於@,橫、豎、斜連著的成為一個塊,問總共有多個@塊。
——>>重刷寒假簡單搜索題,還是不會用scanf或者getchar輸入,失敗。
[cpp] #include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 100 + 10;
char MAP[maxn][maxn];
int cnt, m, n;
int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1};
bool vis[maxn][maxn];
void dfs(int x, int y)
{
vis[x][y] = 1;
for(int i = 0; i < 8; i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if(newx >= 0 && newx < m && newy >= 0 && newy < n && MAP[newx][newy] == '@' && !vis[newx][newy])
dfs(newx, newy);
}
}
int main()
{
int i, j;
while(scanf("%d%d", &m, &n) == 2 && m)
{
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
cin>>MAP[i][j];
cnt = 0;
memset(vis, 0, sizeof(vis));
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
{
if(MAP[i][j] == '@' && !vis[i][j])
{
cnt++;
dfs(i, j);
}
}
printf("%d\n", cnt);
}
return 0;
}
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 100 + 10;
char MAP[maxn][maxn];
int cnt, m, n;
int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1};
bool vis[maxn][maxn];
void dfs(int x, int y)
{
vis[x][y] = 1;
for(int i = 0; i < 8; i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if(newx >= 0 && newx < m && newy >= 0 && newy < n && MAP[newx][newy] == '@' && !vis[newx][newy])
dfs(newx, newy);
}
}
int main()
{
int i, j;
while(scanf("%d%d", &m, &n) == 2 && m)
{
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
cin>>MAP[i][j];
cnt = 0;
memset(vis, 0, sizeof(vis));
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
{
if(MAP[i][j] == '@' && !vis[i][j])
{
cnt++;
dfs(i, j);
}
}
printf("%d\n", cnt);
}
return 0;
}