考虑如下图:
当路径没有权重时,从v1到v7的最短路径代码如下:
#include<iostream>
using namespace std;
int main()
{
int input[8][8] = {
{0,0,0,0,0,0,0,0},
{0,0,1,0,1,0,0,0},
{0,0,0,0,1,1,0,0},
{0,1,0,0,0,0,1,0},
{0,0,0,1,0,1,1,1},
{0,0,0,0,0,0,0,1},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,1,0}
}; //这里简单起见用矩阵表示有向图,并且第一排和第一列元素并不使用
int path[8] = {0,0,0,0,0,0,0,0}; //用于记录经过的节点,因为路径无权重,因此不需要重复处理同一个节点
int i, j;
for (i = 1; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
if (input[i][j] == 1)//如果存在一条路径,则更新目的节点在path中的值
{
if (path[j] == 0)
path[j] = path[i] + 1;//因为无权重,所以这里对起始节点做+1即可
}
}
}
cout << path[7] << endl;
}