題目在此code
解題思路:直接 DFS 或 BFS 就好了。遞歸
以前被 STL 拖事後腿,偏執勁兒又上來了,此次刻意不用 std::queue,本身寫隊列,BFS 不用遞歸,結果就是……代碼又臭又長,讓人不忍直視……隊列
貼出來吧,就當是個教訓。get
#include <cstdio> const int N = 20; char room[N][N]; int W, H; struct point { int x, y; point() {} point(int r, int c) : x(r), y(c) { } } queue[N *N]; int head, tail; void enqueue(const point &p) { queue[tail++] = p; } point &dequeue() { return queue[head++]; } void clear() { head = tail = 0; } bool isEmpty() { return head == tail; } int BFS() { int ans = 0; while (!isEmpty()) { point p = dequeue(); ++ans; if (p.y + 1 < W && room[p.x][p.y + 1] != '#') { enqueue(point(p.x, p.y + 1)); room[p.x][p.y + 1] = '#'; } if (p.x + 1 < H && room[p.x + 1][p.y] != '#') { enqueue(point(p.x + 1, p.y)); room[p.x + 1][p.y] = '#'; } if (p.y - 1 >= 0 && room[p.x][p.y - 1] != '#') { enqueue(point(p.x, p.y - 1)); room[p.x][p.y - 1] = '#'; } if (p.x - 1 >= 0 && room[p.x - 1][p.y] != '#') { enqueue(point(p.x - 1, p.y)); room[p.x - 1][p.y] = '#'; } } return ans; } int main() { while (scanf("%d %d", &W, &H) && (W || H)) { for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { scanf(" %c", &room[i][j]); } } for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (room[i][j] == '@') { enqueue(point(i, j)); room[i][j] = '#'; goto solve; } } } solve: printf("%d\n", BFS()); clear(); } return 0; }