vlambda博客
学习文章列表

Day11 灰灰考研深度优先搜索水池

#include<iostream>#define MAX 100//灰灰考研深度优先遍历/*有一个大小为N*M的园子,雨后积起了水八连通的积水被认为是连载一起的,求园子里一共有多少水池

输入:10 12w........ww..www.....www....ww...ww..........ww..........w....w......w...w.w.....ww.w.w.w.....w..w.w......w...w.......w.

输出3

*/using namespace std;char water[MAX][MAX];bool visited[MAX][MAX];int sum;

void DFStraval(int row, int list, int m, int n) { visited[m][n] = true; if (m - 1 >= 0 && n - 1 >= 0 && visited[m - 1][n - 1] == false && water[m - 1][n - 1] == 'w') DFStraval(row, list, m - 1, n - 1); if (m - 1 >= 0 && visited[m-1][n] == false && water[m-1][n] == 'w') DFStraval(row, list, m-1, n); if (m - 1 >= 0 && n + 1 < list && visited[m - 1][n + 1] == false && water[m - 1][n + 1] == 'w') DFStraval(row, list, m - 1, n + 1); if(n - 1 >= 0 && visited[m][n - 1] == false && water[m][n - 1] == 'w') DFStraval(row, list, m, n - 1); if ( n + 1 < list && visited[m ][n + 1] == false && water[m][n + 1] == 'w') DFStraval(row, list, m, n + 1); if (m + 1 <row && n - 1 >0 && visited[m +1][n - 1] == false && water[m + 1][n - 1] == 'w') DFStraval(row, list, m+1, n - 1); if (m + 1 <row && visited[m + 1][n ] == false && water[m +1][n ] == 'w') DFStraval(row, list, m+1, n); if (m + 1 <row && n + 1 < list && visited[m + 1][n + 1] == false && water[m + 1][n + 1] == 'w') DFStraval(row, list, m+1, n + 1);}

void DFS(int row,int list) { for (int i = 0; i < row; i++) for (int j = 0; j < list; j++) if (visited[i][j] == false && water[i][j] == 'w') { DFStraval(row, list, i, j); sum++; }
}

int main() { int row,list; int i, j,w; while (cin >> row) { sum = 0; cin >> list; memset(visited,false,sizeof(bool)*MAX*MAX);
for (i = 0; i < row; i++) for (j = 0; j < list; j++) cin >> water[i][j];

DFS(row,list); cout << sum << endl;

}}