【C++】最少转机-图的广度优先遍历

最少转机-图的广度优先遍历

1、 题目

小哼和小哈一同坐飞机去旅游。他们现在位于 1 号城市,目标是 5 号城市,可是 1 号城市并没有到 5 号城市的直航。不过小哼已经收集了很多航班的信息,现在小哼希望找到一种乘坐方式,使得转机的次数最少,如何解决呢?


【C++】最少转机-图的广度优先遍历_第1张图片
输入
5 7 1 5
1 2
1 3
2 3
2 4
3 4
3 5
4 5
输出
2

2、代码

#include
#define N 102
#define MAX 999999
using namespace std;
typedef struct Node {
    int x;
    int s;
}node;
int main() {
    node que[N];
    int i, j, k, l;
    int n, m;
    int begin_city, end_city;
    int map[N][N];
    int head=1, tail=1;
    bool book[N] = { 0 };
    bool flag = 0;

    //读入数据
    cin >> n >> m >> begin_city >> end_city;

    //map初始化
    for (i = 1;i <= n;++i) {
        for (j = 1;j <= n;++j) {
            if (i == j)
                map[i][j] = 0;
            else map[i][j] = MAX;
        }
    }
    for (i = 0;i < m;++i) {
        cin >> k >> l;
        map[k][l] = 1;
        map[l][k] = 1;
    }

    //广度优先遍历
    que[tail].x = begin_city;
    que[tail].s = 0;
    tail++;
    book[begin_city] = 1;
    while (head < tail) {
        k = que[head].x;
        for (i = 1;i <= n;++i) {
            //入队
            if (map[head][i] != MAX&&book[i] == 0) {
                que[tail].x = i;
                que[tail].s = que[head].s + 1;
                tail++;
                book[i] = 1;
            }
            //截止条件
            if (que[tail-1].x == end_city) {
                flag = 1;
                break;
            }
        }
        if (flag == 1) {
            break;
        }
        head++;
    }
    cout << que[tail - 1].s << endl;
    system("pause");
    return 0;
}

你可能感兴趣的:(【C++】最少转机-图的广度优先遍历)