DFS and BFS (no-map) Java implementations

Source: Internet
Author: User

 Packagepractice;ImportJava.util.Iterator;ImportJava.util.Stack;Importedu.princeton.cs.algs4.*; Public classTestmain { Public Static voidMain (string[] args) {Graph a=NewGraph (6); A.addedge (2, 4); A.addedge (2, 3); A.addedge (1, 2); A.addedge (0, 5); A.addedge (0, 1); A.addedge (0, 2); A.addedge (3, 4); A.addedge (3, 5);                System.out.println (a); Disposemap DF=NewDisposemap (a); /*Df.dfs (0);        System.out.println (Df.haspathto (1));        System.out.println (Df.haspathto (2));        stack<integer> astack = Df.pathto (1);        while (!astack.isempty ()) {System.out.print (Astack.pop () + ","); } System.out.println ("End");*/Df.bfs (0);  for(inti = 0; I < 6; i++) {System.out.println (df.marked (i)); } Stack<Integer> astack = Df.pathto (4);  while(!Astack.isempty ()) {System.out.print (Astack.pop ()+ "-"); } System.out.println ("End"); }}/** Figure processing Dispose*/classDisposemap {Private Boolean[] marked;//stores a node that has been searched for as true    Private intCount = 0; PrivateGraph G; Private intS//starting point    Private int[] Edgeto;//Edgeto[w] = V,w is the node in the diagram and V is its parent node         PublicDisposemap (Graph G) { This. G =G; Marked=New Boolean[G.V]; Edgeto=New int[G.V];  for(inti = 0; i < marked.length; i++) {Marked[i]=false; }    }    /** Depth-first search, store all points that can be reached from S to start*/     Public voidDfsints) {Marked[s]=true; Count++; System.out.println ("Search" +s);  for(Integer B:g.adj (s)) {//searches for a node that is adjacent to the first node that is not marked            if(Marked[b] = =false) {//if you haven't searched this node, search for it .EDGETO[B] =s;            DFS (b); }        }    }    /** Breadth First search*/     Public voidBFsints) {Edu.princeton.cs.algs4.Queue<Integer> queue =NewQueue<integer>();        Queue.enqueue (s); Marked[s]=true;  while(!Queue.isempty ()) {Integer temp=Queue.dequeue ();  for(Integer B:g.adj (temp)) {//search for all adjacent nodes of a node                if(Marked[b] = =false) {//if you haven't searched this node, search for it .Queue.enqueue (b); EDGETO[B]=temp; MARKED[B]=true; }            }        }    }    /** See if a point is marked*/     Public BooleanMarkedintW) {returnmarked[w];} /** Search a few points*/     Public intCount () {returncount;} /** If there is a path from S to v*/     Public BooleanHaspathto (intv) {returnmarked (v); }    /** S to v path, there is a stack returned, no null is returned*/     PublicStack<integer> Pathto (intv) {Stack<Integer> A =NewStack<integer>();  for(inti = V; I! = s; i =Edgeto[i]) A.push (i);        A.push (s); returnA; }}/** Figure*/classGraph {Bag<integer>[] graph;//Here we use an array of backpacks, an adjacent debit table    intV; intE;  PublicGraph (intV) { This. V =V; Graph= (bag<integer>[])NewBag[v];  for(inti = 0; i < graph.length; i++) {Graph[i]= (bag<integer>)NewBag (); }    }    /** Returns the number of vertices*/     Public intV () {returnV;} /** Returns the number of sides*/     Public intE () {returnE;} /** Add an edge to the diagram*/     Public voidAddedge (intVintW) {Graph[v].add (w);        Graph[w].add (v); E++; }    /** All vertices adjacent to V*/     PublicIterable<integer> Adj (intv) {returnGraph[v]; }    /** Calculate the degree of v*/     Public Static intDegree (Graph G,intv) {intdegree = 0;  for(Integer Bag:g.graph[v]) degree++; returndegree; } @Override Publicstring toString () {string S= V + "vertices," + E + "edges\n";  for(intv = 0; v < V; v++) {s+ = v + ":";  for(Integer integer: This. Adj (v)) {s+ = integer + ""; } s+ = "\ n"; }        returns; }}/** Backpack*/classBag<t>ImplementsIterable<t>{Node first; Private classNode {T value;    Node Next; }         Public voidAdd (T value) {Node Oldfirst=First ; First=NewNode (); First.value=value; First.next=Oldfirst; }         Public voidDelete (T value) {} @Override PublicIterator<t>iterator () {return NewBagiterator (); }        Private classBagiteratorImplementsIterator<t>{node node=First ; @Override Public BooleanHasnext () {returnNode! =NULL; } @Override PublicT Next () {T tempt=Node.value; Node=Node.next; returntempt; }    }}

Non-direction graph in code

Storage of graphs-adjacency table

DFS and BFS (no-map) Java implementations

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.