用邻接矩阵存储
深度、广度遍历图
#include<iostream>
using namespace std;
int a[50][50];
int vd[50];
int visited[50];
int n, e;
#include<queue>
void DFS(int v) {
cout << vd[v]<<" ";
visited[v] = 1;
for (int i = 0; i < n; i++) {
if (a[v][i] != 0 && visited[i] == 0)
DFS(i);
}
}
void BFS(int v) {
queue<int> q;
cout << vd[v] << " ";
visited[v] = 1;
q.push(v);
while (!q.empty()) {
v = q.front();
q.pop();
for (int i = 0; i < n; i++) {
if (a[v][i] != 0 && visited[i] == 0)
{
cout << vd[i] << " ";
visited[i] = 1;
q.push(i);
}
}
}
}
int main() {
cin >> n >> e;
for (int i = 0; i < n; i++)
{
vd[i] = i;
visited[i] = 0;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
for (int m = 0; m < e; m++) {
int i, j, value;
cin >> i >> j >> value;
a[i][j] = value;
}
int v;
cin >> v;
DFS(v);
BFS(v);
system("pause");
}