Title Description
For a forward graph, implement an algorithm to find out if there is a path between two points.
The pointer to the two nodes in the given figure undirectedgraphnode* a, undirectedgraphnode*b(please do not care about the data type, the graph is a graph), please return a bool, Represents whether there is a path between two points (A to B or B to a).
Thought: Breadth First search
The template code is as follows:
Public enum state{ unvisited,visited,visiting;} public static Boolean search (Grapth g,node Start,node end) { //as queue using 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;}
Method 2: Doubt. The code is as follows:
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 (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; }}
*13. Forward path checking