前言:
之前实现过Java版的dfs,bfs:dfs,bfs求最短路径, java实现,现在用c++再实现一次。
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<queue>
#include<stack>
#include<map>
#include<math.h>
#include<set>
#include<list>
#include<string>
#include<cstring>
#define maxn 50
#define INF 0x7fffffff
using namespace std;
int n,m;
char c[maxn][maxn];
bool vis[maxn][maxn];
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
struct coordinate{
int x,y,d;
};
bool isOk(int x,int y,int n,char c[][maxn])
{
if(x>=0&&x<n&&y>=0&&y<n&&!vis[x][y]&&c[x][y]!='#')
return true;
return false;
};
int counter=INF;
int dfs(int x,int y,int d,int n)
{
vis[x][y]=true;
for(int i=0;i<4;i++)
{
int xx=x+dx[i];
int yy=y+dy[i];
//cout<<"xx,yy"<<xx<<" "<<yy<<endl;
if(isOk(xx,yy,n,c))
{
vis[xx][yy]=true;
int dd=d+1;
if(c[xx][yy]=='0')
{
//cout<<"dd:"<<dd<<endl;
if(dd<counter)
counter=dd;
}else
dfs(xx,yy,dd,n);
vis[xx][yy]=false;//»ØËÝ
}
}
return counter;
}
int bfs(int x,int y,int n,char c[][maxn])
{
int counter=0;
queue<coordinate>q;
coordinate first={x,y,0};
vis[x][y]=true;
q.push(first);
while(!q.empty())
{
coordinate top=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int xx=top.x+dx[i];
int yy=top.y+dy[i];
if(isOk(xx,yy,n,c))
{
vis[xx][yy]=true;
int dd=top.d+1;
if(dd>counter)
counter=dd;
if(c[xx][yy]=='0')
return counter;
else
q.push({xx,yy,dd});
}
}
}
return counter;
}
int main(){
int fx=-1;
int fy=-1;
cin>>n;
string str;
for(int i=0;i<n;i++)
{
cin>>str;
for(int j=0;j<str.length();j++)
{
c[i][j]=str[j];
if(str[j]=='@')
{
fx=i;
fy=j;
}
}
}
memset(vis,false,sizeof(vis));
cout<<"dfs:"<<dfs(fx,fy,0,n)<<endl;
memset(vis,false,sizeof(vis));
cout<<"bfs:"<<bfs(fx,fy,n,c)<<endl;
return 0;
}
结果展示: