作者 卫文学
单位 山东科技大学
给出已定的有向图,然后dfs输出序列,和bfs输出序列,如果对于同一个图和同一个初始结点,那么应该按照数字节点大小依次输出,访问后继结点时按照输出顺序依次访问后继结点,题目输入中保证依次输入。【测试用例:物联网工程16级田旭】
输入格式:
先输入图中节点的个数n,和边的条数m。在接下来的m行内,将输入各条边,输入格式为v1 v2,节点编号从1开始
输出格式:
输出序列为两行,第一行为DFS输出序列, 第二行为BFS输出序列,格式为“DFS(或BFS):序列”
输入样例:
在这里给出一组输入。例如:
6 6
1 2
1 6
2 4
2 5
4 3
6 3
输出样例:
在这里给出相应的输出。例如:
DFS: 1 2 4 3 5 6
BFS: 1 2 6 4 5 3
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C++代码:
#include <bits/stdc++.h>
using namespace std;
struct Node {
int index;
Node *next;
};
Node *arr[100];
int visit[100];
queue<Node *> q;
void DFS(Node *root) {
if (!visit[root->index]) {
visit[root->index] = 1;
cout << " " << root->index;
} else return;
Node *p = root->next;
while (p) {
DFS(arr[p->index]);
p = p->next;
}
}
void BFS(Node *root) {
q.push(root);
while (q.size()) {
Node *p = q.front();
if (!visit[p->index]) {
cout << " " << p->index;
visit[p->index] = 1;
p = p->next;
q.pop();
while (p) {
q.push(arr[p->index]);
p = p->next;
}
}else{
q.pop();
}
}
}
int main() {
int n, m;
int x, y;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
arr[i] = new Node;
arr[i]->index = i;
arr[i]->next = NULL;
}
for (int i = 1; i <= m; i++) {
cin >> x >> y;
Node *p = arr[x];
while (p->next) p = p->next;
Node *new_node = new Node;
new_node->index = y;
new_node->next = NULL;
p->next = new_node;
}
cout << "DFS:";
for (int i = 1; i <= n; i++) {
if (!visit[i]) {
DFS(arr[i]);
}
}
cout << endl;
cout << "BFS:";
memset(visit, 0, sizeof(visit));
for (int i = 1; i <= n; i++) {
if (!visit[i]) {
BFS(arr[i]);
}
}
cout << endl;
return 0;
}