编译前提:
Dev C++ [Error] range-based 'for' loops are not allowed in C++98 mode_强哥带你飞的博客-CSDN博客
题目描述
已知无向图G用邻接矩阵存储。
(1)编写一个程序,将图G转化为邻接表
(2)输出图的深度优先遍历结果
(3)输出图的广度优先遍历结果
输入
第一行:节点总数n(n≤10) 下面n行:图G的邻接矩阵
输出
前n行为邻接表,每行格式:当前结点号,若干相邻结点号。 第n+1行:图的深度优先遍历(从1号结点开始) 第n+2行:图的广度优先遍历(从1号结点开始)
样例
输入
4
0 1 1 1
1 0 1 1
1 1 0 0
1 1 0 0
输出
1 2 3 4
2 1 3 4
3 1 2
4 1 2
1 2 3 4
1 2 3 4
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<vector<int>> toAdjList(vector<vector<int>>& matrix) {
int n = matrix.size();
vector<vector<int>> adjList(n + 1);
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (matrix[i][j] == 1) {
adjList[i + 1].push_back(j + 1);
adjList[j + 1].push_back(i + 1);
}
}
}
return adjList;
}
void dfs(vector<vector<int>>& adjList, vector<bool>& visited, vector<int>& result, int curr) {
visited[curr] = true;
result.push_back(curr);
for (int neighbor : adjList[curr]) {
if (!visited[neighbor]) {
dfs(adjList, visited, result, neighbor);
}
}
}
void bfs(vector<vector<int>>& adjList, vector<bool>& visited, vector<int>& result, int start) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int curr = q.front();
q.pop();
result.push_back(curr);
for (int neighbor : adjList[curr]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
}
int main() {
int n;
cin >> n;
vector<vector<int>> matrix(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
vector<vector<int>> adjList = toAdjList(matrix);
vector<bool> visited(n + 1, false);
vector<int> dfsResult, bfsResult;
dfs(adjList, visited, dfsResult, 1);
fill(visited.begin(), visited.end(), false);
bfs(adjList, visited, bfsResult, 1);
for (int i = 1; i <= n; i++) {
cout << i << " ";
for (int neighbor : adjList[i]) {
cout << neighbor << " ";
}
cout << endl;
}
for (int i : dfsResult) {
cout << i << " ";
}
cout << endl;
for (int i : bfsResult) {
cout << i << " ";
}
cout << endl;
return 0;
}