标签:
今天使用深入搜索算法,搜算关于一个水坑的问题。好久没有认真看看C++的书,在该问题上发现自己还有很多地方不熟悉了。
#include <iostream> using namespace std; #define N 10 #define M 12 //首先第一步将当前的地方设置为‘.‘,其次检查所有的其他的地方看是不是符合要求,并进行递归调用 void dfs(int x,int y,char (&field)[N][M]){ field[x][y] = ‘.‘; for (int i = -1; i < 2; ++i) { for (int j = -1; j < 2; ++j) { int nx=x+i,ny=y+j; if (0<=nx && nx <N && 0<=ny && ny<M && (field[nx][ny] == ‘W‘) ) { dfs(nx,ny,field); } } } } int main(int argc, char const *argv[]) { char field[N][M] = { {‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘}, {‘.‘,‘W‘,‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘W‘}, {‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘}, {‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘,‘.‘}, {‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘}, {‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘}, {‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘}, {‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘}, {‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘}, {‘.‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘} }; int res = 0; for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { if (field[i][j]==‘W‘) { dfs(i,j,field); res++; } } } cout<<res<<endl; cout<<"gfs is over!"<<endl; return 0; }
#include <iostream> using namespace std; #define N 10 #define M 12 extern char field[N][M] = { {‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘}, {‘.‘,‘W‘,‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘W‘}, {‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘}, {‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘,‘.‘}, {‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘}, {‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘}, {‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘}, {‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘}, {‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘}, {‘.‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘} }; //首先第一步将当前的地方设置为‘.‘,其次检查所有的其他的地方看是不是符合要求,并进行递归调用 void dfs(int x,int y){ field[x][y] = ‘.‘; for (int i = -1; i < 2; ++i) { for (int j = -1; j < 2; ++j) { int nx=x+i,ny=y+j; if (0<=nx && nx <N && 0<=ny && ny<M && (field[nx][ny] == ‘W‘) ) { dfs(nx,ny); } } } } int main(int argc, char const *argv[]) { int res = 0; for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { if (field[i][j]==‘W‘) { dfs(i,j); res++; } } } cout<<res<<endl; cout<<"gfs is over!"<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/clifff/p/5026639.html