-
D - Knight Moves
- POJ - 1915
- 赛前回顾练手。bfs模板题。
-
#include<iostream> #include<queue> #include<cstring> #include<stdio.h> using namespace std; #define maxn 333 int n,sx,sy,ex,ey,t; bool vis[maxn][maxn]; int to[8][2]= {{-1,2},{1,2},{2,1},{-2,1},{1,-2},{-1,-2},{-2,-1},{2,-1}}; struct node { int x,y,step; } temp,top; bool judge(int x,int y) { if(x<0||y<0||x>=n||y>=n||vis[x][y])return false; return true; } void bfs() { queue<node>q; vis[sx][sy]=1; q.push((node) { sx,sy,0 }); while(!q.empty()) { top=q.front(); q.pop(); if(top.x==ex&&top.y==ey) { printf("%d\n",top.step); return; } for(int i=0; i<8; i++) { temp.x=top.x+to[i][0]; temp.y=top.y+to[i][1]; if(judge(temp.x,temp.y)) { vis[temp.x][temp.y]=1; temp.step=top.step+1; q.push(temp); } } } } int main() { scanf("%d",&t); while(t--) { scanf("%d",&n); scanf("%d%d%d%d",&sx,&sy,&ex,&ey); memset(vis,0,sizeof(vis)); bfs(); } return 0; }
D - Knight Moves POJ - 入门级BFS
最新推荐文章于 2020-07-10 23:49:12 发布