Day11 灰灰考研深度优先搜索水池
Posted cc的心理活动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Day11 灰灰考研深度优先搜索水池相关的知识,希望对你有一定的参考价值。
#include<iostream>
#define MAX 100
//灰灰考研深度优先遍历
/*
有一个大小为N*M的园子,雨后积起了水
八连通的积水被认为是连载一起的,求园子里一共有多少水池
输入:
10 12
w........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;
}
}
以上是关于Day11 灰灰考研深度优先搜索水池的主要内容,如果未能解决你的问题,请参考以下文章