演算法之BFS(廣度優先搜尋演算法)
阿新 • • 發佈:2019-01-08
</pre><pre>
#include<stdio.h> /*有8個城市,編號分別為0~7,求從0號城市到7號城市的最短路線*/ int jz[8][8]= { {0,1,1,1,0,1,0,0}, {1,0,0,0,0,1,0,0}, {1,0,0,1,1,0,0,0}, {1,0,1,0,0,0,1,0}, {0,0,1,0,0,0,1,1}, {1,1,0,0,0,0,0,1}, {0,0,0,1,1,0,0,1}, {0,0,0,0,1,1,1,0}};//0表示不能走,1表示可行 struct { int city,pre; } sq[100]; int qh,qe,i,visited[100]; void out() { printf("%d",sq[qe].city); while(sq[qe].pre!=0) { qe=sq[qe].pre; printf("--%d",sq[qe].city); } } void search(int n) { qh=0; qe=1; sq[1].city=0; sq[1].pre=0; visited[1]=1; while(qh!=qe) //當隊不為空 { qh=qh+1; //結點出隊 for(i=0;i<n;i++) if(jz[sq[qh].city][i]==1&&visited[i]==0) //如果從城市sq[qh].city可以直接到達城市i,且城市i沒有訪問過 { qe=qe+1;//結點入隊 sq[qe].city=i; sq[qe].pre=qh; visited[i]=1; if(sq[qe].city==7) { out(); return ; } } } printf("No Solution!\n"); } int main() { int i,n; n=8; for(i=0;i<n;i++) visited[i]=0; search(n); return 0; }
執行效果圖:
/*迷宮如下,1表示牆,0表示路 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 1 0 1 1 0 1 0 0 1 0 0 0 0 1 1 0 1 0 0 1 0 0 0 0 1 1 1 1 1 1 0 */ #include<stdio.h> /*儲存迷宮矩陣*/ int maze[8][8]={{0,0,0,0,0,0,0,0}, {0,1,1,1,1,0,1,0}, {0,0,0,0,1,0,1,0}, {0,1,0,0,0,0,1,0}, {0,1,0,1,1,0,1,0}, {0,1,0,0,0,0,1,1}, {0,1,0,0,1,0,0,0}, {0,1,1,1,1,1,1,0}}; /*定義方向陣列,如:i+fx[0],j+fy[0],表示向下移動*/ int fx[4]={1,-1,0,0}; int fy[4]={0,0,-1,1}; struct { int x,y,pre; }sq[100]; int qh,qe,i,j,k; void out() { printf("(%d,%d)",sq[qe].x,sq[qe].y); while(sq[qe].pre!=0) { qe=sq[qe].pre; printf("--(%d,%d)",sq[qe].x,sq[qe].y); } } int check(int i,int j) { int flag=1; if(i<0||i>7||j<0||j>7)//是否在迷宮內 flag=0; if(maze[i][j]==1||maze[i][j]==-1) //是否可行 flag=0; return flag; } void search() { qh=0; qe=1; maze[0][0]=-1;//表示訪問過 sq[1].pre=0; sq[1].x=0; sq[1].y=0; while(qh!=qe)//當隊不為空 { qh=qh+1; //出隊 for(k=0;k<4;k++)//搜尋可達到的方塊 { i=sq[qh].x+fx[k]; j=sq[qh].y+fy[k]; if(check(i,j)==1) { qe=qe+1;//入隊 sq[qe].x=i; sq[qe].y=j; sq[qe].pre=qh; maze[i][j]=-1;//表示訪問過 if(sq[qe].x==7&&sq[qe].y==7) { out(); return ; } } } } printf("No Solution!\n"); } int main() { search(); return 0; }
執行效果圖:
PS:每天學到一點點,就很開心