用栈实现图的深度优先搜索Java实现

来源:互联网 发布:twitter第三方登录js 编辑:程序博客网 时间:2024/06/07 23:57

《算法导论》一书中给出的深度优搜索是使用递归方式实现的。相比较而言,用递归的方式实现必用非递归方式实现要好理解很多。但是一般而言所有的递归方式实现都可以用非递归方式实现来代替。这里用一个栈结构来代替递归。初始化时将搜索的源节点压入栈中,只要栈不为空,重复以下操作:

(1)弹出栈顶元素结点

(2)将弹出的栈顶结点的所有邻接后续结点中尚未被发现的结点压入栈中。

具体代码实现如下所示

/** *  * 用栈实现深度优先搜索 * 不能用递归 * @param start */public void DFS(int start){if(checkVertex(start)){System.out.println("==============DFS============");Stack<Integer> stack = new Stack<>();int[] reached = new int[n+1];stack.push(start);for(int i =0;i<n+1;i++)reached[i] = 0;reached[start] = 1;Reached[start] = 1;//4while(!stack.isEmpty()){int head = stack.pop();System.out.println(head);GraphChain list = aList[head];int node = (int) list.pop();while(!list.isEmpty()){if(reached[node]==0){stack.push(node);reached[node] = 1;Reached[node] = 1;}node = (int) list.pop();}}}else{System.out.println("所选起始点超出范围");}}

此代码是基于前面的图结构的(http://blog.csdn.net/john_bian/article/details/74562477)

阅读全文
0 0