Java 图中两节点间的深度优先搜索和广度优先搜索
我有一个无向连通图。我用一个邻接矩阵实现了它,邻接矩阵是一个二维数组 据我所知,DFS在兄弟节点之前访问子节点。BFS先探望兄弟姐妹,再探望孩子 我这样实现了这两个:Java 图中两节点间的深度优先搜索和广度优先搜索,java,data-structures,graph,depth-first-search,breadth-first-search,Java,Data Structures,Graph,Depth First Search,Breadth First Search,我有一个无向连通图。我用一个邻接矩阵实现了它,邻接矩阵是一个二维数组 据我所知,DFS在兄弟节点之前访问子节点。BFS先探望兄弟姐妹,再探望孩子 我这样实现了这两个: public void DFT(int firstVertex) { connectedVertices = 0; int v; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < n
public void DFT(int firstVertex) {
connectedVertices = 0;
int v;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < numVertices; i++) {
if(vertex[i] != null){
vertex[i].setPushed(false);
}
}
stack.push(firstVertex);
connectedVertices++;
vertex[firstVertex].setPushed(true);
while(!stack.isEmpty()){
v = stack.pop();
vertex[v].visit();
for (int i = 0; i < numVertices; i++) {
if(adj[v][i] != 0 && !vertex[i].getPushed()){
stack.push(i);
connectedVertices++;
vertex[i].setPushed(true);
}
}
}
}
public void BFT(int firstVertex) {
connectedVertices = 0;
int v;
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < numVertices; i++) {
if(vertex[i] != null){
vertex[i].setPushed(false);
}
}
queue.add(firstVertex);
connectedVertices++;
vertex[firstVertex].setPushed(true);
while(!queue.isEmpty()){
v = queue.remove();
vertex[v].visit();
for (int i = 0; i < numVertices; i++) {
if(adj[v][i] != 0 && !vertex[i].getPushed()){
queue.add(i);
connectedVertices++;
vertex[i].setPushed(true);
}
}
}
}
public void DFT(int firstVertex){
连通顶点=0;
INTV;
堆栈=新堆栈();
对于(int i=0;i
实际上,这些方法只接受一个参数,即起始顶点。如果要求我将DFS和BFS从一个节点提供给另一个节点,该怎么办?下面是一个简单的连通无向图示例。
如果要求我执行从D到E的DFS,它是D、C、a、E还是D、E。我认为DFS和BFS必须访问每个节点,在这种情况下不能访问B。我不知道应该如何改变我目前的方法来满足这些要求。我不确定你是否先访问C或E。他们都是D的孩子,对吗?这是特定于实现的行为,DFS不定义您首先访问哪个子级 在DFS中,如果您首先选择子C,那么您应该在访问E之前访问A
在BFS中,您应该在访问A或B之前访问E和C。啊,好的,但是如果要求我执行从一个顶点到另一个顶点的dfs或BFS,我是否在到达第二个顶点后立即完成?或者我必须继续并访问其余顶点吗?在上面的示例中,无论我是先访问C还是E,如果结束顶点是E,我都无法访问B。DFS/BFS是否要求您访问连接组件中的每个顶点?@Infodayne如果要求您从D到E搜索(DFS或BFS),那么您应该在到达E后立即停止;您不需要继续。理论上,如果接近起始点,BFS将首先找到顶点;其中,如果距离起点较远,DFS将首先找到顶点。