链接:
http://poj.org/problem?id=1979
题意:
从起点(”标注@的地方“)开始走迷宫,标注“#”的地方不能走,统计一共有多少块可以走
思路:
这题可以转换为,求以起点开始的连通块,所含的位置个数
则只需要:从起点开始,对在迷宫范围内、没有走过,且可以走(不是"#")的迷宫位置,调用DFS进行递归(参数cnt,应设置为传引用,否则cnt应设置为全局变量,这样才能使得每次DFS时,对cnt的更新,可以保存下来
代码:
#include <iostream>
#include <cstring>
#include <string>
#define Clear(x, y) memset(x, y, sizeof(x))
using namespace std;
const int N = 25;
int m, n, startx, starty;
string maze[N];
int vis[N][N];
int d[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
void dfs(int x, int y, int&cnt)
{
if (vis[x][y]) return;
cnt++;
vis[x][y] = 1;
for (int i = 0; i < 4; i++)
{
int nowx = x + d[i][0];
int nowy = y + d[i][1];
if (!vis[nowx][nowy] && nowx >= 0 && nowx < m && nowy >= 0 && nowy < n && maze[nowx][nowy] == '.')
{
dfs(nowx, nowy, cnt);
}
}
}
int main()
{
while (cin >> n >> m && m && n)
{
Clear(vis, 0);
getchar();
for (int i = 0; i < m; i++)
getline(cin, maze[i]);
// for (int i = 0; i < m; i++)
// cout << maze[i] << endl;
//
bool found = false;
for (int i = 0; i < m; i++)
{
if (found)break;
for (int j = 0; j < n; j++)
if (maze[i][j] == '@')
{
found = true;
startx = i;
starty = j;
}
}
int cnt = 0;
dfs(startx, starty, cnt);
cout << cnt << endl;
}
return 0;
}