05-1. List Components (PAT) - 图的遍历问题

For a given undirected graph with N vertices and E edges, please list all the connected components by both DFS and BFS. Assume that all the vertices are numbered from 0 to N-1. While searching, assume that we always start from the vertex with the smallest index, and visit its adjacent vertices in ascending order of their indices.

Input Specification:

Each input file contains one test case. For each case, the first line gives two integers N (0<N<=10) and E, which are the number of vertices and the number of edges, respectively. Then E lines follow, each described an edge by giving the two ends. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in each line a connected component in the format "{ v1 v2 ... vk }". First print the result obtained by DFS, then by BFS.

Sample Input:

8 6
0 7
0 1
2 0
4 1
2 4
3 5

Sample Output:

{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }

题意:给出图中各个顶点的连通关系,要求输出DFS与BFS的遍历结果解题思路:根据输入建立邻接矩阵,再进行图的遍历,注意:图中可能不是所有顶点都连通的,因此需要对图中每个顶点进行遍历
#include <iostream>
#include <string>
#include <memory.h>
using namespace std;

typedef struct Graph{
    int *graphMatrix;
    bool *visited;
    int vertexNumber;
}*pGraph, nGraph;

typedef struct{
    int *queData;
    int queFront;
    int queEnd;
    int MaxSize;
}*pQue, nQue;

pGraph CreateGraph( int vertexNumber );
pGraph InsertEdge( pGraph pG, int edgeStart, int edgeEnd );
void DFS( pGraph pG, int vertex );
pQue CreateQueue( int queSize );
bool IsEmptyQ( pQue pQ );
void AddQ( pQue pQ, int item );
int DeleteQ( pQue pQ );
void BFS( pGraph pG, int vertex, int vertexNum );

int main()
{
    int N, E;
    cin >> N >> E;
    pGraph pG;
    pG = CreateGraph( N );
    int i;
    int    edgeStart, edgeEnd;
    for ( i = 0; i < E; i++ )
    {
        cin >> edgeStart >> edgeEnd;
        InsertEdge( pG, edgeStart, edgeEnd );
    }
    for ( i = 0; i < N; i++ )
    {
        if ( pG->visited[i] == false )
        {
            cout << "{ ";
            DFS( pG, i);
            cout << "}" << endl;
        }
    }
    for ( i = 0; i < N; i++ )    //清空visited状态
    {
        pG->visited[i] = false;
    }
    for ( i = 0; i < N; i++ )
    {
        if ( pG->visited[i] == false )
        {
            cout << "{ ";
            BFS( pG, i, N);
            cout << "}" << endl;
        }
    }
    return 0;
}

pGraph CreateGraph( int vertexNumber )
{
    pGraph pG;
    pG = ( pGraph )malloc( sizeof( nGraph ) );
    pG->vertexNumber = vertexNumber;
    int len = ( vertexNumber * ( vertexNumber + 1 ) / 2 );
    pG->graphMatrix = ( int* )malloc( len * sizeof( int ) );
    memset( pG->graphMatrix, 0, sizeof( int ) * len);
    pG->visited = ( bool* )malloc( vertexNumber * sizeof( bool ) );
    memset( pG->visited, false, sizeof( bool ) * vertexNumber );
    return pG;
}

pGraph InsertEdge( pGraph pG, int edgeStart, int edgeEnd )
{
    if ( edgeStart >= pG->vertexNumber || edgeEnd >= pG->vertexNumber )
    {
        cout << "Error Edge!" << endl;
        return pG;
    }
    int tmp;
    if ( edgeStart < edgeEnd )
    {
        tmp = edgeStart;
        edgeStart = edgeEnd;
        edgeEnd = tmp;
    }
    int item = edgeStart * ( edgeStart + 1 ) / 2 + edgeEnd;
    pG->graphMatrix[item] = 1;
    return pG;
}

void DFS( pGraph pG, int vertex )
{
    if ( pG->visited[vertex] == false )
    {
        cout << vertex << ‘ ‘;
    }
    pG->visited[vertex] = true;
    int    rows, cols;
    int materixIndex;
    for ( cols = 0; cols < vertex; cols++ )    //扫描行
    {
        materixIndex = vertex * ( vertex + 1 ) / 2 + cols;
        if ( pG->graphMatrix[materixIndex] == 1 && pG->visited[ cols ] == false )
        {
            DFS( pG, cols );
        }
    }
    for ( rows = vertex; rows < pG->vertexNumber; rows++ )
    {
        materixIndex = rows * ( rows + 1 ) / 2 + vertex;
        if ( pG->graphMatrix[materixIndex] == 1 && pG->visited[ rows ] == false )
        {
            DFS( pG, rows );
        }
    }
}

pQue CreateQueue( int queSize )
{
    pQue pQ;
    pQ = ( pQue )malloc( sizeof( nQue ) );
    pQ->MaxSize = queSize + 1;
    pQ->queData = ( int * )malloc( pQ->MaxSize * sizeof( int ) );
    pQ->queFront = pQ->queEnd = 0;
    return pQ;
}

bool IsEmptyQ( pQue pQ )
{
    if ( pQ->queFront == pQ->queEnd )    //队列为空
    {
        return true;
    }
    else
    {
        return false;
    }
}

void AddQ( pQue pQ, int item )
{
    if ( ( pQ->queEnd + 1 ) % pQ->MaxSize == pQ->queFront  )
    {
        cout << "Queue Is Full!" << endl;
        return;
    }
    pQ->queEnd = ( pQ->queEnd + 1 ) % pQ->MaxSize;
    pQ->queData[ pQ->queEnd ] = item;
}

int DeleteQ( pQue pQ )
{
    if ( pQ->queFront == pQ->queEnd )
    {
        cout << "Queue Is Empty!" << endl;
        return -1;
    }
    else
    {
        pQ->queFront = ( pQ->queFront + 1 ) % pQ->MaxSize;
        return pQ->queData[ pQ->queFront ];
    }
}

void BFS( pGraph pG, int vertex, int vertexNum )
{
    cout << vertex << ‘ ‘;
    pG->visited[vertex] = true;
    pQue pQ;
    pQ = CreateQueue( vertexNum );
    AddQ( pQ, vertex);
    int cols, rows;
    int materixIndex;
    while ( IsEmptyQ( pQ ) != true )
    {
        vertex = DeleteQ( pQ );
        for ( cols = 0; cols < vertex; cols++ )    //扫描行
        {
            materixIndex = vertex * ( vertex + 1 ) / 2 + cols;
            if ( pG->graphMatrix[materixIndex] == 1 && pG->visited[ cols ] == false )
            {
                cout << cols << ‘ ‘;
                pG->visited[cols] = true;
                AddQ( pQ, cols );
            }
        }
        for ( rows = vertex; rows < pG->vertexNumber; rows++ )
        {
            materixIndex = rows * ( rows + 1 ) / 2 + vertex;
            if ( pG->graphMatrix[materixIndex] == 1 && pG->visited[ rows ] == false )
            {
                cout << rows << ‘ ‘;
                pG->visited[rows] = true;
                AddQ( pQ, rows );
            }
        }
    }
}
时间: 2024-10-18 08:28:12

05-1. List Components (PAT) - 图的遍历问题的相关文章

05-2. Saving James Bond - Easy Version (PAT) - 图的遍历问题

This time let us consider the situation in the movie "Live and Let Die" in which James Bond, the world's most famous spy, was captured by a group of drug dealers. He was sent to a small piece of land at the center of a lake filled with crocodile

05-3. 六度空间 (PAT) - 图的遍历问题

“六度空间”理论又称作“六度分隔(Six Degrees of Separation)”理论.这个理论可以通俗地阐述为:“你和任何一个陌生人之间所间隔的人不会超过六个,也就是说,最多通过五个人你就能够认识任何一个陌生人.”如图6.4所示. 图6.4 六度空间示意图 “六度空间”理论虽然得到广泛的认同,并且正在得到越来越多的应用.但是数十年来,试图验证这个理论始终是许多社会学家努力追求的目标.然而由于历史的原因,这样的研究具有太大的局限性和困难.随着当代人的联络主要依赖于电话.短信.微信以及因特网

图的遍历 | 1034 map处理输入数据,连通块判断

这题写得比较痛苦.首先有点不在状态,其次题目比较难读懂. "Gang"成立的两个条件:①成员数大于两个  ②边权总和大于阈值K 首先,在录数据的时候通过map或者字符串哈希建立string到int的映射. 然后,这个题的数据结构其实是带权无向图.在录数据的时候就要处理好点权和边权. 最后,对所有顶点做一遍dfs,汇总边权,找出最大点权和最大点权所在的点,把数据录进ans里. 注意的点一个是环路边权的汇总.方法是在dfs中通过先加边权再判断vis是否遍历过.此时又要注意用不搜前驱点的df

图的遍历 | 1076 bfs

bfs踩了很多坑才写完.注意:出队时不做是否vis判断,但是要加上vis[出队顶点]=1 .入队时进行判断,并且也要 vis[入队顶点]=1 #include <stdio.h> #include <memory.h> #include <math.h> #include <string> #include <vector> #include <set> #include <stack> #include <queu

42. 蛤蟆的数据结构笔记之四十二图的遍历之广度优先

42. 蛤蟆的数据结构笔记之四十二图的遍历之广度优先 本篇名言:"生活真象这杯浓酒 ,不经三番五次的提炼呵 , 就不会这样一来可口 ! -- 郭小川" 继续看下广度优先的遍历,上篇我们看了深度遍历是每次一个节点的链表是走到底的. 欢迎转载,转载请标明出处:http://write.blog.csdn.net/postedit/47029275 1.  原理 首先,从图的某个顶点v0出发,访问了v0之后,依次访问与v0相邻的未被访问的顶点,然后分别从这些顶点出发,广度优先遍历,直至所有的

算法导论--图的遍历(DFS与BFS)

转载请注明出处:勿在浮沙筑高台http://blog.csdn.net/luoshixian099/article/details/51897538 图的遍历就是从图中的某个顶点出发,按某种方法对图中的所有顶点访问且仅访问一次.为了保证图中的顶点在遍历过程中仅访问一次,要为每一个顶点设置一个访问标志.通常有两种方法:深度优先搜索(DFS)和广度优先搜索(BFS).这两种算法对有向图与无向图均适用. 以下面无向图为例: 1.深度优先搜索(DFS) 基本步骤: 1.从图中某个顶点v0出发,首先访问v

图的遍历总结

概念 图的遍历有两种遍历方式:深度优先遍历(depth-first search)和广度优先遍历(breadth-first search). 1.深度优先遍历 基本思路:首先从图中某个顶点V0出发,然后依次从V0相邻的顶点出发深度优先遍历,直至图中所有与V0路径相通的顶点都被访问了:若此时尚有顶点未被访问,则从中选一个顶点作为起始点,重复上述过程,直到所有的顶点都被访问.可以看出深度优先遍历是一个递归的过程. 如下图中的一个无向图: 其深度优先遍历得到的序列为: 0->1->3->7-

41 蛤蟆的数据结构笔记之四十一图的遍历之深度优先

41  蛤蟆的数据结构笔记之四十一图的遍历之深度优先 本篇名言:"对于我来说 , 生命的意义在于设身处地替人着想 , 忧他人之忧 , 乐他人之乐. -- 爱因斯坦" 上篇我们实现了图的邻接多重表表示图,以及深度遍历和广度遍历的代码,这次我们先来看下图的深度遍历. 欢迎转载,转载请标明出处: 1.  原理 图遍历又称图的遍历,属于数据结构中的内容.指的是从图中的任一顶点出发,对图中的所有顶点访问一次且只访问一次.图的遍历操作和树的遍历操作功能相似.图的遍历是图的一种基本操作,图的许多其它

java实现图的遍历(深度优先遍历和广度优先遍历)

package arithmetic.graphTraveral;import java.util.LinkedList;import java.util.Queue; /** * 这个例子是图的遍历的两种方式 * 通过它,使我来理解图的遍历 * Created on 2013-11-18 * @version 0.1 */public class GraphTraveral{ // 邻接矩阵存储图 // --A B C D E F G H I // A 0 1 0 0 0 1 1 0 0 //