(无向)图的遍历,最常用的是深度优先遍历,此外还有广度优先遍历,与搜索算法相似。要记得标记已经访问的结点。
(一)深度优先遍历
以s为起点遍历,再以 与s有边相连的点为起点再遍历。由栈(递归调用)实现;
#include <iostream>
using namespace std;
int n, m, s;
int a[2001][2001];
bool visited[2001]; //访问标记
void build_graph() {
int x, y;
cin >> n >> m >> s;
for(int i=1; i<=m; i++) {
cin >> x >> y;
a[x][y] = a[y][x] = 1;
}
}
void dfs(int x) { //以x为起点深搜
if(visited[x] == true) return;
visited[x] = true;
cout << x << " -> ";
for(int i=1; i<=n; i++)
if(!visited[i] && a[x][i] == 1) //x和y有边相连并且i没有访问过
dfs(i);
}
int main() {
build_graph();
dfs(s); //以s为起点深搜
}
(二)广度优先遍历(层次遍历)
以s为起点,把s入队列,再循环:出队列得到k,再将k的所有相关点入队列。由队列实现;
C++ STL<queue> 解:
#include <iostream>
#include <queue>
using namespace std;
int n, m, s;
int a[2001][2001];
int visited[2001]; //访问标记
bool inq[2001]; //在不在队列中
queue<int> q;
void build_graph() {
int x, y;
cin >> n >> m >> s;
for(int i=1; i<=m; i++) {
cin >> x >> y;
a[x][y] = a[y][x] = 1;
}
}
void bfs(int x) {
int k;
q.push(x);
inq[x] = true;
while(!q.empty()) {
k = q.front();
q.pop();
cout << k << " -> ";
visited[k] = true;
inq[k] = false;
for(int i=1; i<=n; i++) {
if(a[k][i] == 1 && !visited[i] && !inq[i]) {
q.push(i);
inq[i] = true;
}
}
}
}
int main() {
build_graph();
bfs(s);
return 0;
}
QWQ ...