1. 程式人生 > >『一本通』廣搜的優化技巧

『一本通』廣搜的優化技巧

node https continue bfs () check header strong nbsp

Knight Moves

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int dx[9]={2,2,1,1,-1,-1,-2,-2},dy[9]={-1,1,-2,2,-2,2,-1,1};
 4 int n,L,step[305][305];
 5 struct node{int x,y;}b,e; 
 6 queue<node>q;
 7 bool check(int x,int y) {return x>=0&&x<L&&y>=0&&y<L;}
8 9 void BFS() { 10 while(!q.empty()) q.pop(); 11 memset(step,0x7f,sizeof(step)); 12 q.push(b),step[b.x][b.y]=0; 13 while(step[e.x][e.y]>1e3) { 14 int X=q.front().x,Y=q.front().y; q.pop(); 15 for(int i=0;i<8;i++) { 16 int nx=X+dx[i],ny=Y+dy[i]; 17 if
(!check(nx,ny)||step[nx][ny]<1e3) continue; 18 step[nx][ny]=step[X][Y]+1; 19 q.push((node){nx,ny}); 20 } 21 } 22 printf("%d\n",step[e.x][e.y]); 23 } 24 25 int main() { 26 scanf("%d",&n); 27 while(n--) { 28 scanf("%d%d%d%d%d",&L,&b.x,&b.y,&e.x,&e.y);
29 if(b.x==e.x&&b.y==e.y) puts("0"); 30 else BFS(); //Breadth-First Search(廣度優先搜索) 31 } 32 }

『一本通』廣搜的優化技巧