题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200811011015899.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JldGFfX18=,size_16,color_FFFFFF,t_70)
解法
BFS
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
bool mp[10][10];
bool vis[10][10];
int dx[8]={-1,0,1,-1,1,-1,0,1};
int dy[8]={1,1,1,0,0,-1,-1,-1};
int m,n;
int ans=inf;
struct node{
int x,y,step;
}now,next,start,end;
queue<node> q;
bool judge(int x,int y){
if(x==0||y==0||x>m||y>n||vis[x][y]||mp[x][y]) return false;
return true;
}
void bfs(void){
q.push(start);
while(!q.empty()){
now=q.front();
q.pop();
if(now.x==end.x&&now.y==end.y){
ans=min(ans,now.step);
return;
}
for(int i=0;i<8;i++){
if(judge(now.x+dx[i],now.y+dy[i])){
next.x=now.x+dx[i],next.y=now.y+dy[i],next.step=now.step+1;
q.push(next);
vis[next.x][next.y]=true;
}
}
}
}
int main(){
cin>>m>>n;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
cin>>mp[i][j];
start.x=1,start.y=1,start.step=0;end.x=m,end.y=n;
vis[1][1]=true,bfs();
ans==inf?puts("cbl can not find his npy"):printf("%d",ans);
return 0;
}
DFS
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
bool mp[10][10];
bool vis[10][10];
int dx[8]={-1,0,1,-1,1,-1,0,1};
int dy[8]={1,1,1,0,0,-1,-1,-1};
int m,n;
int ans=inf;
bool judge(int x,int y){
if(x==0||y==0||x>m||y>n||vis[x][y]||mp[x][y]) return false;
return true;
}
void dfs(int x,int y,int step){
if(x==m&&y==n){
ans=min(ans,step);
return;
}
if(step>=ans) return;
for(int i=0;i<8;i++){
int nx=x+dx[i],ny=y+dy[i];
if(judge(nx,ny)){
vis[nx][ny]=true;
dfs(nx,ny,step+1);
vis[nx][ny]=false;
}
}
}
int main(void){
cin>>m>>n;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
cin>>mp[i][j];
vis[1][1]=true;
dfs(1,1,0);
ans==inf?puts("cbl can not find his npy"):printf("%d",ans);
return 0;
}
DFS剪枝版本
#include<bits/stdc++.h>
using namespace std;
bool mp[10][10];
bool vis[10][10];
int dx[8]={-1,0,1,-1,1,-1,0,1};
int dy[8]={1,1,1,0,0,-1,-1,-1};
int m,n;
int ans=-1;
bool judge(int x,int y){
if(x==0||y==0||x>m||y>n||vis[x][y]||mp[x][y]) return false;
return true;
}
bool ida(int x,int y,int step,int maxstep){
if(step>maxstep) return false;
if(x==m&&y==n) return true;
for(int i=0;i<8;i++){
int nx=x+dx[i],ny=y+dy[i];
if(judge(nx,ny)){
vis[nx][ny]=true;
if(ida(nx,ny,step+1,maxstep)) return true;
vis[nx][ny]=false;
}
}
return false;
}
int main(void){
cin>>m>>n;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
cin>>mp[i][j];
vis[1][1]=true;
for(int i=1;i<=m*n;i++){
if(ida(1,1,0,i)){
ans=i;
break;
}
}
ans==-1?puts("cbl can not find his npy"):printf("%d",ans);
return 0;
}