题意:一个二维数组,给定起点,有些地方能走,有些地方不能走,求从起点出发最多能走过多少点
分析:dfs和bfs都行,注意两者实现的细节差异
dfs代码:
#include<iostream>
using namespace std;
int d[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char a[100][100];
int n,m,tot;
void dfs(int x,int y)
{
if(a[x][y]=='#') return;
a[x][y]='#';
tot++;
for(int i=0;i<4;i++){
int dx=x+d[i][0];
int dy=y+d[i][1];
if(dx>=0&&dx<m&&dy>=0&&dy<n){
dfs(dx,dy);
}
}
}
int main()
{
int sx,sy;
while(cin>>n>>m){
if(!n&&!m) break;
tot=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
if(a[i][j]=='@'){
sx=i,sy=j;
}
}
}
dfs(sx,sy);
cout<<tot<<endl;
}
}
bfs代码:
#include<iostream>
#include<queue>
using namespace std;
int d[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char a[100][100];
int n,m,tot;
struct node{
int x,y;
};
queue<node> q;
void bfs()
{
while(!q.empty()){
node tmp=q.front();
q.pop();
for(int i=0;i<4;i++){
node tmp2;
tmp2.x=tmp.x+d[i][0];
tmp2.y=tmp.y+d[i][1];
if(tmp2.x>=0&&tmp2.x<m&&tmp2.y>=0&&tmp2.y<n&&a[tmp2.x][tmp2.y]!='#'){
a[tmp2.x][tmp2.y]='#';
tot++;
q.push(tmp2);
}
}
}
}
int main()
{
while(cin>>n>>m){
if(!n&&!m) break;
while(!q.empty()) q.pop();
tot=0;
node tmp;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
cin>>a[i][j];
if(a[i][j]=='@'){
tmp.x=i,tmp.y=j;
a[i][j]='#'; // 注意这里
}
}
tot=1; // 注意这里
q.push(tmp);
bfs();
cout<<tot<<endl;
}
}