您的位置:首页 > 其它

邻接矩阵存储简单路径

2015-06-16 14:47 246 查看
Description

假设无向图G采用邻接矩阵存储,设计一个算法,输出图G中从顶点u到v的所有简单路径。

Input

简单路径是指路径上的顶点不重复。第一行为一个整数n,表示顶点的个数(顶点编号为0到n-1),第二行表示顶点u和v的编号,接下来是为一个n*n大小的矩阵,表示图的邻接关系。数字为0表示不邻接,1表示不邻接。

Output

输出图G中从顶点u到v的所有简单路径。

Sample Input

1
2
3
4
5
6
7

5
0 3
0 1 0 1 1
1 0 1 1 0
0 1 0 1 1
1 1 1 0 1
1 0 1 1 0

Sample Output

1
2
3
4
5
6
7
8

0123
01243
013
03
04213
0423
043

#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct
{
int edge[100][100];
}MGraph;
MGraph g;
int  i, j, n, vis[31],path[31];
char V[31];
void bfs(int x,int y,int cnt)
{
int i;
vis[x] = 1;
path[cnt] = x;
if (x == y)
{
for (i = 0; i <= cnt; i++)
cout << path[i];
cout << endl;
}
for (i = 0; i < n; i++)
{
if (g.edge[x][i] && !vis[i])
{
//vis[i] = 1;
bfs(i, y, cnt + 1);
}
}
vis[x] = 0;
}
int main()
{
int x, y;
cin >> n >> x >> y;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
cin >> g.edge[i][j];
bfs(x,y,0);
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: