*13. Forward path checking

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.