题目链接
题目大意是求@直接相邻或者间接相邻(斜对角)所形成的区块数;
解题思路是利用bfs/dfs来找出所形成的区块数。
dfs算法:(一次走到底)
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char maze[101][101];
bool mark[101][101];
int n, m;
int go[][2] = { 1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,-1,-1,1 };
void dfs(int x, int y)
{
for (int i = 0;i < 8;i++)
{
int nx = x + go[i][0];
int ny = y + go[i][1];
if (nx<1 || nx>n || ny<1 || ny>m) continue;
if (maze[nx][ny] == '*') continue;
if (mark[nx][ny] == true)continue;
mark[nx][ny] = true;
dfs(nx, ny);
}
return;
}
int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
if (m == 0 && n == 0) break;
for (int i = 1;i <= n;i++)
scanf("%s", maze[i]+1);
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++)
{
mark[i][j] = false;
}
int ans = 0;
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++)
{
if (mark[i][j] == true) continue;
if (maze[i][j] == '*') continue;
dfs(i, j);
ans++;
}
}
printf("%d\n", ans);
}
return 0;
}
bfs代码:(按层次走)
#pragma warning(disable:4996);
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
struct fuck{
int x, y;
};
queue<fuck> q;
char maze[101][101];
bool mark[101][101];
int n, m;
int go[][2] = { 1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,-1,-1,1 };
void dfs()
{
while (q.empty() == false)
{
fuck now = q.front();
q.pop();
for (int i = 0;i < 8;i++)
{
int nx = now.x + go[i][0];
int ny = now.y + go[i][1];
if (nx<1 || nx>n || ny<1 || ny>m) continue;//越界
if (maze[nx][ny] == '*') continue;
if (mark[nx][ny] == true)continue;
mark[nx][ny] = true;
fuck tmp;
tmp.x = nx;
tmp.y = ny;
q.push(tmp);
}
}
return;
}
int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
if (m == 0 && n == 0) break;
for (int i = 1;i <= n;i++)
scanf("%s", maze[i]+1);
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++)
{
mark[i][j] = false;
}
while (q.empty() == false) q.pop();
int ans = 0;
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++)
{
if (mark[i][j] == true) continue;
if (maze[i][j] == '*') continue;
fuck tmp;
tmp.x = i;
tmp.y = j;
q.push(tmp);
dfs();
ans++;
}
}
printf("%d\n", ans);
}
return 0;
}