DFS就可以解决,只要想到要向四个方向搜索就可以解决了,很多写法,最直白的就是不断判断,然后判断....
注意:特别注意输入的两个变量,全程小心!!!!
#include<iostream> #include<string.h> using namespace std; int n, m,ans; char maze[21][21]; bool vised[21][21]; //查找从(x,y)开始的可以移动的黑点的数量,直接DFS int DFS(int x, int y){ vised[x][y] = true; if (x >= 1 && !vised[x - 1][y] && maze[x - 1][y] == '.'){ ans++; vised[x - 1][y] = true; DFS(x - 1, y); } if (x<m-1&& !vised[x+1][y] && maze[x+1][y] == '.'){ vised[x + 1][y] = true; ans++; DFS(x+1, y); } if (y>= 1 && !vised[x][y-1] && maze[x][y-1] == '.'){ vised[x][y - 1] = true; ans++; DFS(x, y-1); } if (y<n- 1 && !vised[x][y+1] && maze[x][y+1] == '.'){ vised[x][y + 1] = true; ans++; DFS(x, y+1); } return ans; } int main() { while (cin >>n>>m){ if (n == 0 && m == 0) break; ans = 1; memset(vised, false, sizeof(vised)); int sx, sy; for (int i = 0; i <m; i++){ for (int j = 0; j <n; j++){ cin >> maze[i][j]; if (maze[i][j] == '@'){ sx = i, sy = j; } } } DFS(sx, sy); cout <<ans<< endl; } return 0; }
原文地址:http://blog.csdn.net/hujian_/article/details/44759309