已知若干个城市的地图,求从一个城市到另一个城市的路径,要求路径中经过的城市最少。
#include<iostream> #include<cstring> using namespace std; int ju[9][9]= {{0,0,0,0,0,0,0,0,0}, {0,1,0,0,0,1,0,1,1}, {0,0,1,1,1,0,1,1,1}, {0,0,1,0,0,1,1,1,1}, {0,0,1,0,1,1,1,0,1}, {0,1,1,0,1,1,1,0,0}, {0,0,0,1,1,1,1,1,0}, {0,1,1,1,0,0,1,1,0}, {0,1,1,1,1,0,0,0,1}}; int a[101],b[101],s[9],head,tail; void print(int d) { cout << char(a[d]+64); while(b[d]){ d=b[d]; cout << "--" << char(a[d]+64); } cout << endl; } void bfs() { int i; head=0;tail=1; //tail依次记录每个节点 a[1]=1;b[1]=0;s[1]=1; //a数组记录每个节点上城市,b数组记录上一个城市的节点,s记录走过的城市 do{ head++; for(i=1;i<=8;i++){ if(ju[a[head]][i]==0 && s[i]==0){ tail++; a[tail]=i; b[tail]=head; s[i]=1; if(i==8) { print(tail); return; } } } }while(head<tail); } int main() { memset(s,0,sizeof(s)); bfs(); return 0; }