题目描述
已知无向图G已用邻接矩阵存储。
问题描述:(1)编写一个程序,将图G转化为邻接表
(2)输出图的深度优先遍历结果
输入
第一行:节点总数n
下面n行:图G的邻接矩阵
输出
前n行为邻接表,每行格式:当前结点号,若干相邻结点号。
第n+1行:图的深度优先遍历(从1号结点开始)
样例
提示
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
void convertToAdjList(vector<vector<int>>& adjMatrix, vector<vector<int>>& adjList) {
int n = adjMatrix.size();
for (int i = 0; i < n; i++) {
vector<int> neighbors;
for (int j = 0; j < n; j++) {
if (adjMatrix[i][j] == 1) {
neighbors.push_back(j + 1);
}
}
adjList.push_back(neighbors);
}
}
void dfs(vector<vector<int>>& adjList, vector<bool>& visited, int node) {
stack<int> s;
s.push(node);
while (!s.empty()) {
int curr = s.top();
s.pop();
if (!visited[curr]) {
visited[curr] = true;
cout << curr << " ";
for (int i = adjList[curr - 1].size() - 1; i >= 0; i--) {
int neighbor = adjList[curr - 1][i];
if (!visited[neighbor]) {
s.push(neighbor);
}
}
}
}
}
int main() {
int n;
cin >> n;
vector<vector<int>> adjMatrix(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> adjMatrix[i][j];
}
}
vector<vector<int>> adjList;
convertToAdjList(adjMatrix, adjList);
for (int i = 0; i < n; i++) {
sort(adjList[i].begin(), adjList[i].end());
cout << i + 1;
for (int neighbor : adjList[i]) {
cout << " " << neighbor;
}
cout << endl;
}
vector<bool> visited(n + 1, false);
dfs(adjList, visited, 1);
cout << endl;
return 0;
}