弗洛伊德最优路径法
给定一个有N个顶点和E条边的无向图,请判断给定的两个顶点之间是否有路径存在。 假设顶点从0到N−1编号。纯技术需求贴
望广大鱼友鼎力相助
输入格式:
输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。
随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。
最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。
输出格式:
如果i和j之间存在路径,则输出"There is a path between i and j.",
否则输出"There is no path between i and j."。
输入样例1:
7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 3
输出样例1:
There is a path between 0 and 3.
输入样例2:
7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 6
输出样例2:
There is no path between 0 and 6.
从一个顶点开始遍历无向图,看能否遍历到另一个顶点。
看起来这是某种练习题吧,这种题还是自己写的好,毕竟这是基础啊 Croper 发表于 2019-5-19 21:56
从一个顶点开始遍历无向图,看能否遍历到另一个顶点。
看起来这是某种练习题吧,这种题还是自己写的好,毕 ...
老师说;用弗洛伊德最优解,和并查集,最后还有人用DFS做出来的,感觉无力呵 用Java写的,唉!!
import java.util.Scanner;
public class Main {
static int visited[]= {0,0,0,0,0,0,0,0,0,0,0};
static int lianxi[][]= {
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0}
};
static int p=0;
public static void main(String[] args) {
//int visited[]= {0,0,0,0,0,0,0,0,0,0};
int N,E;
Scanner scanf=new Scanner(System.in);
N=scanf.nextInt();
E=scanf.nextInt();
for(int i=0;i<E;i++) {
int x=scanf.nextInt();
int y=scanf.nextInt();
lianxi=1;
lianxi=1;
}
int i,j;
i=scanf.nextInt();
j=scanf.nextInt();
DFS(i,N,j);
if(p==1)
System.out.printf("There is a path between %d and %d.",i,j);
else
System.out.printf("There is no path between %d and %d.",i,j);
}
public static void DFS(int v,int n,int j) {
if(v==j) {
p=1;
return;
}
visited=1;
for(int i=0;i<n;i++) {
if(visited==0&&lianxi==1) {
DFS(i, n, j);
}
}
}
}
页:
[1]