深搜基础题目 杭电 HDU 1241

时间:2023-03-08 16:08:32
深搜基础题目 杭电 HDU  1241

HDU 1241 是深搜算法的入门题目,递归实现。

原题目传送门:

http://acm.hdu.edu.cn/showproblem.php?pid=1241

代码仅供参考,c++实现:

#include <iostream>
using namespace std; char land[][];
int p,q; void dfs(int x,int y){
land[x][y] = '*';
if(land[x-][y]!= '@' && land[x+][y] != '@' && land[x][y-] != '@' && land[x][y+] != '@' && land[x-][y+]!= '@' && land[x+][y-] != '@' && land[x-][y-] != '@' && land[x+][y+] != '@')
return ; if(x+ > && y+ > && x+ <= p && y+ <= q && land[x+][y+]== '@') { dfs(x+,y+); }
if(x+ > && y- > && x+ <= p && y- <= q && land[x+][y-]== '@') { dfs(x+,y-); }
if(y- > && x- > && x- <= p && y- <= q && land[x-][y-]== '@') { dfs(x-,y-); }
if(y+ > && x- > && x- <= p && y+ <= q && land[x-][y+]== '@') { dfs(x-,y+); } if(x+ > && y > && x+ <= p && y <= q && land[x+][y]== '@') { dfs(x+,y); }
if(x- > && y > && x- <= p && y <= q && land[x-][y]== '@') { dfs(x-,y); }
if(y- > && x > && x <= p && y- <= q && land[x][y-]== '@') { dfs(x,y-); }
if(y+ > && x > && x <= p && y+ <= q && land[x][y+]== '@') { dfs(x,y+); } return ;
}
int main(int argc, const char * argv[]) { int num;
cin>>p>>q;
while(p> && q>){ num = ;
for(int i = ; i <= p ;i++){
for(int j = ; j<= q; j++){
cin>>land[i][j];
}
}
for(int i = ; i <= p ;i++){
for(int j = ; j<= q; j++){
if(land[i][j] == '@'){
num++;
dfs(i,j);
} }
}
cout<< num<<endl;
cin>>p>>q;
}
return ;
}