解题(DirGraCheckPath--有向图的遍历(深度搜索))
Posted hzy1234
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解题(DirGraCheckPath--有向图的遍历(深度搜索))相关的知识,希望对你有一定的参考价值。
题目描述
对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。
给定图中的两个结点的指针DirectedGraphNode* a, DirectedGraphNode* b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。
代码如下:
1 package com.yzh.hehe; 2 3 import java.util.ArrayList; 4 import java.util.Stack; 5 6 7 public class DirGraCheckPath { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 12 } 13 14 public boolean checkPath(UndirectedGraphNode a, UndirectedGraphNode b) { 15 return checkSingle(a, b)||checkSingle(b, a); 16 } 17 18 private boolean checkSingle(UndirectedGraphNode a, UndirectedGraphNode b) { 19 if (a.label==b.label) { 20 return true; 21 } 22 //深度优先遍历用堆栈实现(广度优先遍历用队列实现) 23 Stack<UndirectedGraphNode> stack= new Stack<UndirectedGraphNode>(); 24 //已遍历的点 25 ArrayList<UndirectedGraphNode> list=new ArrayList<UndirectedGraphNode>(); 26 list.add(a); 27 stack.addAll(a.neighbors); 28 UndirectedGraphNode temp = null; 29 //深度遍历一个点,看是否目标点,是结束,否则再将此点的连接点放入栈中等待遍历重复(入栈将连接点中已经在栈中和已遍历过的点去掉)。 30 while (!stack.isEmpty()) { 31 temp = stack.pop(); 32 if (temp.label==b.label) { 33 return true; 34 } 35 for (UndirectedGraphNode undirectedGraphNode : temp.neighbors) { 36 if (!stack.contains(undirectedGraphNode)&&!list.contains(undirectedGraphNode)) { 37 stack.push(undirectedGraphNode); 38 } 39 } 40 list.add(temp); 41 } 42 return false; 43 } 44 45 } 46 class UndirectedGraphNode { 47 int label = 0; 48 UndirectedGraphNode left = null; 49 UndirectedGraphNode right = null; 50 ArrayList<UndirectedGraphNode> neighbors = new ArrayList<UndirectedGraphNode>(); 51 52 public UndirectedGraphNode(int label) { 53 this.label = label; 54 } 55 }
以上是关于解题(DirGraCheckPath--有向图的遍历(深度搜索))的主要内容,如果未能解决你的问题,请参考以下文章