定义一有n个结点的的以邻接矩阵为存储方式的网(有向或无向均可),并对其进行如下操作: 1.深度优先遍历,并输出遍历序列; 2.广度优先遍历,并输出遍历序列; 3.求源点到图中每个点的最短路径,并输出;C++代码
时间: 2024-03-25 18:35:28 浏览: 16
好的,我会为你解答这个问题。
首先,我们需要定义一个表示邻接矩阵的结构体,包括结点数量和邻接矩阵本身:
```cpp
const int MAXN = 100;
struct Graph {
int n;
int mat[MAXN][MAXN];
};
```
接下来,我们需要实现深度优先遍历和广度优先遍历。这两种遍历算法可以使用递归和队列来实现。这里我们分别定义两个函数 `dfs` 和 `bfs`:
```cpp
bool vis[MAXN]; // 标记每个点是否已经遍历过
// 深度优先遍历
void dfs(Graph g, int u) {
vis[u] = true;
cout << u << " "; // 输出遍历顺序
for (int v = 0; v < g.n; v++) {
if (g.mat[u][v] && !vis[v]) {
dfs(g, v);
}
}
}
// 广度优先遍历
void bfs(Graph g, int u) {
queue<int> q;
q.push(u);
vis[u] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
cout << u << " "; // 输出遍历顺序
for (int v = 0; v < g.n; v++) {
if (g.mat[u][v] && !vis[v]) {
q.push(v);
vis[v] = true;
}
}
}
}
```
最后,我们需要实现求最短路径的函数 `shortest_path`。这个函数可以使用 Dijkstra 算法或者 Floyd-Warshall 算法来实现。这里我们使用 Dijkstra 算法,同时也需要定义一个结构体 `Node` 来表示每个结点:
```cpp
struct Node {
int d; // 到源点的距离
int p; // 前驱结点
};
// Dijkstra 算法求最短路径
void shortest_path(Graph g, int s) {
Node nodes[MAXN];
for (int i = 0; i < g.n; i++) {
nodes[i].d = INT_MAX;
nodes[i].p = -1;
}
nodes[s].d = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push(make_pair(0, s));
while (!pq.empty()) {
pair<int, int> top = pq.top();
pq.pop();
int u = top.second;
if (nodes[u].d < top.first) continue;
for (int v = 0; v < g.n; v++) {
if (g.mat[u][v] && nodes[v].d > nodes[u].d + g.mat[u][v]) {
nodes[v].d = nodes[u].d + g.mat[u][v];
nodes[v].p = u;
pq.push(make_pair(nodes[v].d, v));
}
}
}
for (int i = 0; i < g.n; i++) {
if (nodes[i].p != -1) {
cout << "Shortest path from " << s << " to " << i << " is: ";
int j = i;
stack<int> st;
while (j != -1) {
st.push(j);
j = nodes[j].p;
}
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
cout << "with distance " << nodes[i].d << endl;
}
}
}
```
完整的代码如下: