【发布时间】:2015-03-26 18:08:12
【问题描述】:
我必须在图形上使用 DFS,然后在反向图形上使用,并且图形是有向的。我很好奇,不是首先将邻接列表反转为另一个邻接列表,然后将其复制回原始邻接列表,然后再次调用 DFS,有什么方法可以让我知道我必须使用邻接来编写 DFS 函数以相反的方式列出。以下是我的 Java 代码,我用它来判断我的图是否是强连接的。我会非常有帮助的。简而言之,我想避免 rev_graph 函数并最小化我的代码。
import java.util.*;
class Strongly_conn
{
static ArrayList<LinkedList<Integer>> g;
static ArrayList<LinkedList<Integer>> g1;
static int []visited;
public static void create_graph()
{
int n,i,k,j;
Scanner s=new Scanner(System.in);
System.out.println("enter the value of number of vertices");
n=s.nextInt();
visited=new int[n];
for(i=0;i<n;++i)
visited[i]=0;
g=new ArrayList<LinkedList<Integer>>();
for(i=0;i<n;++i)
{
g.add(new LinkedList<Integer>());
System.out.println("enter the number of vertices adjacent to "+ (i+1)+" and what are they?" );
k=s.nextInt();
for(j=1;j<=k;++j)
g.get(i).add(s.nextInt());
}
}
public static void main(String []args)
{
int so,i;
Scanner s=new Scanner(System.in);
create_graph();
System.out.println("enter any vertex");
so=s.nextInt();
DFS(so);
for(i=0;i<g.size();++i)
if(visited[i]==1)
continue;
else {System.out.println("the directed graph is not strongly connected");System.exit(0);}
for(i=0;i<g.size();++i)
visited[i]=0;
rev_graph();
DFS(so);
for(i=0;i<g.size();++i)
if(visited[i]==1)
continue;
else {System.out.println("the directed graph is not strongly connected");System.exit(0);}
System.out.println("the directed graph is strongly connected");
}
public static void DFS(int s)
{
visited[s-1]=1;
for(int e:g.get(s-1))
if(visited[e-1]==0)
DFS(e);
else continue;
}
public static void rev_graph()
{
int i;
g1=new ArrayList<LinkedList<Integer>>();
for(i=0;i<g.size();++i)
g1.add(new LinkedList<Integer>());
for(i=0;i<g.size();++i)
for(int e:g.get(i))
g1.get(e-1).add(i+1);
g=new ArrayList<LinkedList<Integer>>(g1);
}
}
【问题讨论】:
标签: java graph depth-first-search