题目链接:http://poj.org/problem?id=1979
深度优先搜索非递归写法
#include <cstdio>
#include <stack> using namespace std;
const int MAX_W = , MAX_H = ;
char Map[MAX_W][MAX_H+];
int W, H; int DFS(int sx, int sy); int main()
{
while (scanf("%d %d", &H, &W) ==
&& W != && H != ) {
for (int i = ; i < W; i++)
scanf("%s", Map[i]);
for (int i = ; i < W; i++)
for (int j = ; j < H; j++) {
if (Map[i][j] == '@')
printf("%d\n", DFS(i, j));
}
}
return ;
} int DFS(int sx, int sy)
{
int dx[] = {, , -, }, dy[] = {, , , -};
int Visited[MAX_W][MAX_H] = {};
typedef pair<int, int> Position;
stack<Position> sta; Visited[sx][sy] = ;
int num = ;
Map[sx][sy] = '.';
sta.push(Position(sx, sy)); while (!sta.empty()) {
Position p = sta.top(); sta.pop();
for (int i = ; i < ; i++) {
int nx = p.first + dx[i], ny = p.second + dy[i];
if ( <= nx && nx < W && <= ny && ny < H &&
Map[nx][ny] == '.' && !Visited[nx][ny]) {
sta.push(Position(nx, ny));
Visited[nx][ny] = ;
num++;
}
}
}
return num;
}