【題目】據美國動物分類學家內斯特·邁爾推算,世界上有超過100萬種動物,各種動物都有自己的語言,假設動物A可以與動物B進行通信,但它不能與動物C通信,動物C只能與動物B通信,所以動物A、B之間的通信需要動物B來當翻譯,問兩個動物之間相互通信至少需要多少個翻譯。
C++版代碼
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
#define MAXV 4
//問題表示
int A[MAXV][MAXV]; //圖的鄰接矩陣
int n,m,k;
int sno,eno;
int visited[MAXV];
struct NodeType
{
int vno; //頂點編號
int length; //路徑長度
};
int bfs(int sno,int eno) //廣度優先搜索算法
{
if (sno==eno) return 0;
NodeType e,e1;
queue<NodeType> qu; //定義隊列
e.vno=sno;
e.length=0;
qu.push(e); //結點e進隊
visited[e.vno]=1;
while (!qu.empty()) //隊列不空循環
{
e=qu.front(); qu.pop(); //出隊結點e
if(e.vno==eno)
return e.length-1;
for(int j=0;j<n;j++)
{
if(A[e.vno][j]!=0) //到頂點j有邊
{
if(visited[j]==0)
{
e1.vno=j;
e1.length=e.length+1;
qu.push(e1);
visited[j]=1;
}
}
}
}
return -1;
}
int main()
{
while (scanf_s("%d%d",&n,&m)==2)
{
int a,b,i;
memset(A,0,sizeof(A));
memset(visited,0,sizeof(visited));
for(i=0;i<m;i++) //根據輸入建立鄰接矩陣
{
scanf_s("%d%d",&a,&b);
A[a][b]=1; //無向圖
A[b][a]=1;
}
scanf_s("%d",&k);
for(i=0;i<k;i++)
{
scanf_s("%d %d",&sno,&eno);
printf("%d\n",bfs(sno,eno));
}
}
return 0;
}