码迷,mamicode.com
首页 > 其他好文 > 详细

链式前向星BFS

时间:2016-04-16 21:02:42      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

采用链式前向星的BFS:

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long LL;

const int maxN = 100 + 3;
const int maxM = 1000 + 3;
int head[maxN];
int visited[maxN];
int N, M;

struct EdgeNode
{
    int to;
    int w;
    int next;
};
EdgeNode Edges[maxM];

void BFS(int x)
{
    memset(visited, 0, sizeof(visited));
    queue<int> initQueue;
    for(int i = 1; i <= N; i++)
    {
        if( !visited[i] )
        {
            visited[i] = 1;
            initQueue.push( i );
            while( !initQueue.empty() )
            {
                i = initQueue.front(); //取得对头的节点,一定是下次待扩展的节点
                initQueue.pop();//队顶元素出队(出队代表着访问到了这个节点)
            //遍历与当前节点相连的节点
                for(int j = head[i]; j !=  -1; j = Edges[j].next)
                {
                  //如果没被访问,入队
                    if( !visited[ Edges[j].to ])
                    {
                        visited[ Edges[j].to ] = 1;
                        initQueue.push( Edges[j].to );
                    }
                }
            }
        }
    }
}

int main()
{
    freopen("input.txt", "r", stdin);
    memset(head, -1, sizeof(head));
    cin >> N >> M;
    for(int i = 1; i <= M; i++)
    {
        int x, y ,z;
        cin >> x >> y >> z;
        Edges[i].to = y;
        Edges[i].w = z;
        Edges[i].next = head[x];
        head[x] = i;
    }
    memset(visited, 0, sizeof(visited));
    BFS(1);
    return 0;
}

 

链式前向星BFS

标签:

原文地址:http://www.cnblogs.com/Ash-ly/p/5399068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!