• ACM题目————图的广度优先搜索


    题目描述

    图的广度优先搜索类似于树的按层次遍历,即从某个结点开始,先访问该结点,然后访问该结点的所有邻接点,再依次访问各邻接 点的邻接点。如此进行下去,直到所有的结点都访问为止。在该题中,假定所有的结点以“A”--“Z”中的若干字符表示,且要求结点的访问顺序要求根据由 “A”至“Z”的字典顺序进行访问。

    输入
    输入只包含一个测试用例,第一行为一个自然数n,表示顶点的个数,第二行为n个大写字母构成的字符串,表示顶点,接下来是为一个n*n大小的矩阵,表示图的邻接关系。数字为0表示不邻接,否则为相应的边的长度。
    最后一行为一个字符,表示要求进行广度优先搜索的起始顶点。
    输出
    用一行输出广度优先搜索结果,起始点为给定的顶点,各顶点之间用一个空格隔开。要求同一顶点的邻接点的访问顺序按“A”---“Z”的字典顺序。
    样例输入
    5
    HUEAK
    0 0 2 3 0
    0 0 0 7 4
    2 0 0 0 0
    3 7 0 0 1
    0 4 0 1 0
    H
    样例输出
    H A E K
    //Asimple
    #include <stdio.h>
    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <string.h>
    #include <queue>
    
    using namespace std;
    const int maxn = 101;
    int n, T, num, cnt, point, line, x, y;
    int start_x, start_y, end_x, end_y;
    string str;
    char ch;
    queue<int> q;
    int vis[maxn];//标记数组,标记是否走过
    char Map[maxn][maxn];//地图
    int a[26];
    
    void BFS(char ch)
    {
        int v;
        q.push(ch-'A');
        while ( !q.empty() )
        {
            memset(a,0,sizeof(a));
            v = -1 ;
            for(int i=0; i<n; i++)
                if( vis[i]==0 && str[i] == q.front()+'A' )
                {
                    vis[i] = 1 ;
                    if( v == -1 ) v = i ;
                }
            if( v == -1 ) break ;
            printf( cnt ++ ==0 ? "%c" : " %c", str[v]);
            for(int i=0; i<n; i++)
                if(vis[i]==0 && Map[v][i] )
                    a[str[i]-'A'] ++ ;
            for(int i=0; i<26; i++)
                for(int j=0; j<a[i]; j++)
                    q.push(i);
            q.pop();
        }
    }
    
    int main()
    {
        cin >> n >> str ;
        for (int i = 0; i < n; i ++ )
            for (int j = 0; j < n; j ++ )
            {
                cin >> num ;
                Map[i][j] = num ;
            }
        cin >> ch ;
        BFS(ch);
    
        return 0;
    }
    
    低调做人,高调做事。
  • 相关阅读:
    Interesting Finds: 2009 01.15 ~ 01.17
    Interesting Finds: 2008.12.07
    Interesting Finds: 2008.12.31
    10月16号
    10月14号
    10月15号
    10月13号
    10月20号
    10月19号
    10月12号
  • 原文地址:https://www.cnblogs.com/Asimple/p/5543832.html
Copyright © 2020-2023  润新知