洛谷p1443 马的遍历,我采用的是bfs,但是不知道哪里出错了过不了,想了很久,还是没搞明白,希望大家可以帮我看看
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
const int N=410;
struct pos{
int x;
int y;
int steps;
};
int n,m,Startx,Starty;
int vis[N][N];
int bx[8]={-1,-2,-2,-1,1,2,2,1};
int by[8]={-2,-1,1,2,-2,-1,1,2};
int check(int x,int y){
if(x<1||x>n||y<1||y>m)
return 0;
return 1;
}
void bfs(int endx,int endy){
pos cur,next;
queue<pos>que;
cur.x=Startx;
cur.y =Starty;
cur.steps =0;
que.push(cur);
vis[cur.x][cur.y ]=1;
while(!que.empty()){
cur=que.front();
que.pop();
if(cur.x==endx&&cur.y ==endy){
printf("%d ",cur.steps );
return ;
}
//接下来要循环八个方向
//使用方向数组
for(int i=0;i<8;i++){
next.x=cur.x+bx[i];
next.y=cur.y+by[i];
next.steps =cur.steps +1;
if(check(next.x,next.y)==1){
if(vis[next.x][next.y ]==0)
vis[next.x ][next.y ]=1;
que.push(next);
}
}
}
printf("-1\n");
return ;
}
int main(){
cin>>n>>m>>Startx>>Starty;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++)
bfs(i,j);
printf("\n");
}
return 0;
}