nyoj-58

来源:互联网 发布:国际贸易数据查询 编辑:程序博客网 时间:2024/04/30 08:15

bfs

#include<iostream>#include<queue>#include<string.h>using namespace std;struct node{int x,y,cnt;};int x[4]={-1,0,1,0};int y[4]={0,1,0,-1};int startx,starty,endx,endy;int map[9][9]=  {      {1,1,1,1,1,1,1,1,1},      {1,0,0,1,0,0,1,0,1},      {1,0,0,1,1,0,0,0,1},      {1,0,1,0,1,1,0,1,1},      {1,0,0,0,0,1,0,0,1},      {1,1,0,1,0,1,0,0,1},      {1,1,0,1,0,1,0,0,1},      {1,1,0,1,0,0,0,0,1},      {1,1,1,1,1,1,1,1,1}  };  int v[9][9];int bfs(){queue<node> q;node n,t;n.x=startx;n.y=starty;n.cnt=0;memset(v,0,sizeof(v));v[startx][starty]=1;q.push(n);while(!q.empty()){n=q.front();q.pop();if(n.x==endx && n.y==endy)return n.cnt;for(int i=0;i<4;++i){t.x=n.x+x[i];t.y=n.y+y[i];t.cnt=n.cnt+1;if(t.x>=0 && t.x<=8 && t.y>=0 && t.y<=8 && !v[t.x][t.y] && !map[t.x][t.y]){q.push(t);v[t.x][t.y]=1;}}}}int main(){int t;cin>>t;while(t--){cin>>startx>>starty>>endx>>endy;cout<<bfs()<<endl;}return 0;}

  

原创粉丝点击