图的深度优先遍历:城市地图
从城市1到城市5,要求找出乘车时间最短的方案:
数据给出形式如下:
1 2 3 4 5 6 7 8 9
| 5 8 1 2 2 1 5 10 2 3 3 2 5 7 3 1 4 3 4 4 4 5 5 5 3 3
|
第一行的5表示有5个城市1,2,3,4,5;8表示有8条公路。
接下来8行是a b c形式的三组数据,表示:有一条路可以从城市a到城市b,乘车耗时c分钟。
若道路为单向车道(即有向图),求出从城市1到城市5的最短时间
若道路为双向车道(即无向图),求出从城市1到城市5的最短时间
解题代码
整体代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include<iostream> using namespace std;
int city, road; int minLeng=9999999;
void dfs(int** cityMap, bool* book, int now,int leng = 0,int target=5) { if (leng > minLeng) return; if (now == target) { if (leng < minLeng) { minLeng = leng; } return; }
for (int i = 0; i < city + 1; i++) { if (cityMap[now][i] > 0 && book[i] == false) { book[i] = true; dfs(cityMap, book, i, leng + cityMap[now][i], target); book[i] = false; } }
return; }
int main() { cin >> city >> road;
int** cityMap = new int* [city + 1]; for (int i = 0; i < city + 1; i++) { cityMap[i] = new int[city + 1]; for (int j = 0; j < city + 1; j++) { cityMap[i][j] = -1; } }
bool* book = new bool[city + 1]; for (int i = 0; i < city + 1; i++) book[i] = false;
int a, b, c; for (int i = 0; i < road; i++) { cin >> a >> b >> c; cityMap[a][b] = c; cityMap[b][a] = c; }
dfs(cityMap, book, 1); cout << minLeng; return 0; }
|
数据的录入代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| int main() { cin >> city >> road;
int** cityMap = new int* [city + 1]; for (int i = 0; i < city + 1; i++) { cityMap[i] = new int[city + 1]; for (int j = 0; j < city + 1; j++) { cityMap[i][j] = -1; } }
bool* book = new bool[city + 1]; for (int i = 0; i < city + 1; i++) book[i] = false;
int a, b, c; for (int i = 0; i < road; i++) { cin >> a >> b >> c; cityMap[a][b] = c; cityMap[b][a] = c; }
dfs(cityMap, book, 1); cout << minLeng; return 0; }
|
注意给邻接矩阵赋值的时候,有向图赋值一次,无向图在与主对角线对称的位置还要再赋值一次
DFS代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| void dfs(int** cityMap, bool* book, int now,int leng = 0,int target=5) { if (leng > minLeng) return; if (now == target) { if (leng < minLeng) { minLeng = leng; } return; }
for (int i = 0; i < city + 1; i++) { if (cityMap[now][i] > 0 && book[i] == false) { book[i] = true; dfs(cityMap, book, i, leng + cityMap[now][i], target); book[i] = false; } }
return; }
|
运行结果
单向道为9,双向道为7