题目描述
对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。
给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode*b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。
思想:广度优先搜索
模板代码如下:
public enum State{ Unvisited,Visited,Visiting; } public static boolean search(Grapth g,Node start,Node end){ //当做队列使用 LinkedList<Node> q=new LinkedList<Node>(); for(Node u:g.getNodes()){ u.state=State.Unvisited; } start.state=State.Visiting; q.add(start); Node u; while(!q.isEmpty()){ u=q.removeFirst(); if(u!=null){ for(Node v:u.getAdjacent()){ if(v.state==State.Unvisited){ if(v==end){ return true; }else{ v.state=State.Visiting; q.add(v); } } } u.state=State.Visited; } } return false; }
方法2:存疑。代码如下:
import java.util.*; /* public class UndirectedGraphNode { int label = 0; UndirectedGraphNode left = null; UndirectedGraphNode right = null; ArrayList<UndirectedGraphNode> neighbors = new ArrayList<UndirectedGraphNode>(); public UndirectedGraphNode(int label) { this.label = label; } }*/ public class Path { public boolean checkPath(UndirectedGraphNode a, UndirectedGraphNode b) { return check(a,b) || check(b,a); } boolean check(UndirectedGraphNode a, UndirectedGraphNode b){ if(a==b) return true; for(int i=0;i<a.neighbors.size();i++){ return check(a.neighbors.get(i),b); } return false; } }