NYOJ 54最少步數
阿新 • • 發佈:2019-02-04
這道題關鍵的就是怎麼用佇列去儲存訪問的節點,用結構體,在用c++的佇列,其他的就是基本的bfs
別人的程式碼
我的程式碼:#include<iostream> #include<stdio.h> #include<queue> #include<cstring> using namespace std; int a[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 b[4]={-1,1,0,0};//**往上下左右四個方向**// int c[4]={0,0,-1,1}; int visit[9][9]; struct node { int x,y;//**座標**// int step;//**步數**// }; queue<node> Q; int bfs(int x1,int y1,int x2,int y2) { int i,s,t; node e={x1,y1,0};//**從(x1,y1)開始,步數首先定義為0**// Q.push(e);//**將可以走的方格都插入到佇列**// visit[x1][y1]=1;//**標記visit[x1][y1]曾經被訪問過**// while(!Q.empty())//如果佇列不為空**// { e=Q.front(); //**e設為佇列的第一個元素**// if(e.x==x2 && e.y==y2)//如果找到就跳出迴圈**// { break; } Q.pop();//**取出佇列的第一個元素**// for(i=0;i<4;i++) { s=e.x+b[i];//四個方向進行搜尋**// t=e.y+c[i]; if(s>=0 && s<=8 && t>=0 && t<=8 && !visit[s][t] && a[s][t]==0)//**曾經訪問過這個格子或者這個格子不能繼續走**// { node e1={s,t,e.step+1};//**步數+1**// Q.push(e1);//**插入步數+1的元素**// visit[s][t]=1;//**標記visit[s][t]被訪問過**// } } } if(Q.empty())//**進入死衚衕,到達不了**// { return -1; } while(!Q.empty())//**如果佇列不為空**// { Q.pop();//**清空佇列**// } return e.step;//**返回最少步數**// } int main() { int k,s,x1,x2,y1,y2; scanf("%d",&s); while(s--) { scanf("%d %d %d %d",&x1,&y1,&x2,&y2); memset(visit,0,sizeof(visit)); k=bfs(x1,y1,x2,y2); printf("%d\n",k); } return 0; }
#include<algorithm> #include<iostream> #include<cstdio> #include<cstdlib> #include<vector> #include<string> using namespace std; typedef struct { int x; int y; }point; vector<point> v; 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 step[9][9]; int vis[9][9]; point p; bool ok; int index; int start_x, start_y, end_x, end_y; int bfs(int x, int y, int time) // time 每次記錄當前的步數 { if(x==end_x && y==end_y) { ok = true; return 0; } if(x-1>=0&&y>=0&&!vis[x-1][y]&&map[x-1][y]==0) //依次搜尋 { step[x-1][y] = time+1; p.x = x-1; p.y = y; vis[x-1][y] = 1; v.push_back(p); } if(x>=0&&y+1<9&&!vis[x][y+1]&&map[x][y+1]==0) { step[x][y+1] = time+1; p.x = x; p.y = y+1; vis[x][y+1] = 1; v.push_back(p); } if(x+1<9&&!vis[x+1][y]&&map[x+1][y]==0) { step[x+1][y] = time+1; p.x = x+1; p.y = y; vis[x+1][y] = 1; v.push_back(p); } if(y-1>=0&&!vis[x][y-1]&&map[x][y-1]==0) { step[x][y-1] = time+1; p.x = x; p.y = y-1; vis[x][y-1] = 1; v.push_back(p); } } int main() { int ncase; scanf("%d",&ncase); while(ncase--) { cin>>start_x>>start_y>>end_x>>end_y; //memset(step,0,sizeof(step)); for(int i=0; i<9; i++) for(int j=0; j<9; j++) { step[i][j] = 0; vis[i][j] = 0; } p.x = start_x; p.y = start_y; v.clear(); //step[p.x][p.y]=0; v.push_back(p); ok = false; index = 0; while(!ok) { bfs(v[index].x, v[index].y, step[v[index].x][v[index].y]); index++; } cout<<step[end_x][end_y]<<endl; } system("pause"); return 0; }