Problem D 找路径
Description
在一个无向图中,请你按深搜列出从指定的起点到终点的所有路径,及路径的长度。每个节点只能走一次。
Input
有多组测试数据,每组的第一行有两个整数m、n,m、n不超过10,m是顶点的个数,n是连接两点的路径数。接着有n行,每行形如s、t、v,表示从s到t的长度是v。1是起点,m是终点。
Ouput
按样例输出。
Sample Input
7 8
1 2 3
1 4 3
1 6 4
2 3 1
3 4 2
4 7 2
6 5 5
5 7 6
Sample Output
Case 1:
1>2>3>4>7 8
1>4>7 5
1>6>5>7 15
如图所示:
实验代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int local[12][12];
int book[12];
int counts=0;
void dfs(int start, int end) {
if (start == end) {
cout <<" "<<counts<<endl;
return;
}
for (int i = 1; i <= end; i++) {
if (local[start][i] > 0 && book[i] == 0) {
if (start == 1) {
cout << "1";
counts = 0;
}
book[i] = 1;
cout << ">" << i;
counts += local[start][i];
dfs(i, end);
book[i] = 0;
}
}
}
int main()
{
int m, n,id=1;
cin >> m >> n;
for (int i = 1; i <= n; i++) {
int p;
int q;
cin >> p >> q;
cin>>local[p][q];
local[q][p] = local[q][p];
}
for (int i = 1; i <= m; i++) {
book[i] = 0;
}
book[1] = 1;
cout << "Case "<<id++<<":"<< endl;
dfs(1, m);
return 0;
}