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

摘自《啊哈算法》:小哼和小哈一同坐飞机去旅游,他们现在位于1号城市,目标是5号城市,可是1号城市并没有直接到5号城市的直航. 不过小哼已经收集到了很多航班的信息,现在小哼希望找到一中乘坐方式,使得转机的次数最少?

《最少转机——图的广度优先遍历》

Solution:深度优先遍历是不可以啊,DFS的思想会使得遍历的不一定是最少的

可以运用BFS思想

Code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define INF 999999

struct note
{
	int x;     /// 城市编号
	int s;     /// 转机次数
};

int book[100];

int main(int argc, char const *argv[])
{
	int i, j, m, n, cur;
	int a, b, e[101][101];
	int head, tail;
	int start, end;
	int flag = 0;
	struct note que[101];

	scanf("%d %d %d %d", &n, &m, &start, &end);
	for(i = 1; i <= n; ++i)
	{
		for(j = 1; j <= n; ++j)
		{
			if(i == j)
			{
				e[i][j] = 0;
			}
			else
			{
				e[i][j] = INF;
			}
		}
	}

	for(i = 1; i <= m; ++i)
	{
		scanf("%d %d", &a, &b);
		e[a][b] = 1;
		e[a][b] = 1;
	}

	head = 1;
	tail = 1;

	que[tail].x = start;
	que[tail].s = 0;
	++tail;
	book[1] = 1;

	while(head < tail)
	{
		cur = que[head].x;
		for(i = 1; i <= n; ++i)
		{
			if(e[cur][i] == 1 && book[i] == 0)
			{
				que[tail].x = i;
				que[tail].s = que[head].s + 1;
				tail++;
				book[i] = 1;
			}

            if(que[tail-1].x == end)       /// 达到目标城市, 退出循环
            {
                flag = 1;
                break;
            }
		}

		if(flag)
		{
			break;
		}

		head++;
	}

	printf("%d\n", que[tail-1].s);
	system("pause");
	return 0;
}
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/triumph92/article/details/41654267
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞