数据结构-怀化学院期末题(322)

图的深度优先搜索

题目描述:

图的深度优先搜索类似于树的先根遍历,是树的先根遍历的推广。即从某个结点开始,先访问该结点,然后深度访问该结点的第一棵子树,依次为第二顶子树。如此进行下去,直到所有的结点都访问为止。在该题中,假定所有的结点以"A"至"Z"中的若干字符表示,且要求结点的访问顺序根据"A"至"Z"的字典顺序进行访问。例如有如下图:

如果要求从H开始进行深度优先搜索,则搜索结果为:H->A->K->U->E.

输入:

输入只包含一个测试用例,第一行为一个自然数n,表示顶点的个数,第二行为n个大写字母构成的字符串,表示顶点,接下来是为一个n*n大小的矩阵,表示图的邻接关系。数字为0表示不邻接,否则为相应的边的长度。

最后一行为一个字符,表示要求进行深度优先搜索的起始顶点。

输出:

用一行输出深度优先搜索结果,起始点为给定的顶点,各顶点之间用一个空格隔开(注意后面的提示)。

样例输入:

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 K U E

代码:

cpp 复制代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
typedef pair<int,int> PII;
const int N = 1e5 + 10;
int n;
string str;
int a[26][26],book[26];
char c;
int main(){
	cin >> n;
	cin >> str;
	for(int i = 0;i < n;i ++)
		for(int j = 0;j < n;j ++)
			cin >> a[str[i] - 'A'][str[j] - 'A'];
	cin >> c;
	stack<int> st;
	st.push(c-'A');
	book[c-'A'] = 1;
	cout << c << ' ';
	while(st.size()){
		auto t = st.top();
		st.pop();
		if(!book[t]) 
			cout << (char)(t + 'A') << " ";
		book[t] = 1;
		for(int i = 25;i >= 0;i --){
			if(a[t][i] != 0 && book[i] == 0){
				st.push(i);
			}
		}
		
	}
	return 0;
}
相关推荐
Fanxt_Ja3 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1233 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1124 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19434 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww4 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚4 天前
[数据结构] 排序
数据结构
睡不醒的kun4 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌4 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long4 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn4 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap