題目描述
圖的廣度優先搜索類似於樹的按層次遍歷,即從某個結點開始,先訪問該結點,然后訪問該結點的所有鄰接點,再依次訪問各鄰接 點的鄰接點。如此進行下去,直到所有的結點都訪問為止。在該題中,假定所有的結點以“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;
}
