这题深搜的的话,我们进入一个点的时候,我们就把步数加一,然后这个点标记为0,然后再向其他的方向走,这是正确的思路。
错误的思路就是,先走向四个方向,然后标记下一个方向的点,然后进入dfs,这个思路没有太大的毛病,但是有一个问题,如果周围都不能走,那我们就不能通过原点之后的下一个点,再次走回原点了,这个思路就错在这个地方。
#include <iostream>
#include <cstring>
using namespace std;
int w, h, r, c, ans;
int map[25][25];
int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void dfs(int x,int y)
{
ans++;
map[x][y] = 0;
for (int i = 0; i < 4;i++) {
int row = x + d[i][0];
int col = y + d[i][1];
if (row<h&&row>=0&&col>=0&&col<w&&map[row][col]) {
dfs(row, col);
}
}
}
int main()
{
ios::sync_with_stdio(false);
while (cin>>w>>h&&w+h) {
memset(map, 0, sizeof(map));
char ch;
for (int i = 0; i < h;i++) {
for (int j = 0; j < w;j++) {
cin >> ch;
if (ch=='.')
map[i][j] = 1;
else if (ch=='@') {
r = i;
c = j;
map[r][c] = 1;
}
}
}
ans = 0;
dfs(r,c);
cout << ans << endl;
}
return 0;
}