The Java implementation of BFS and DFS

Source: Internet
Author: User

<pre name= "code" class= "java" >import java.util.hashmap;import java.util.linkedlist;import java.util.Queue;/* The breadth traversal is traversing to a vertex and then visiting its connection point, A, B. Then visit A's connection table, very natural, this data structure is hashmap, with vertex as key. Save a connection table for each vertex */public class BFS {static int count=0;/* * Hashmap<character,linkedlist<character>> graph This hashmap is the adjacency table used to store each node in the graph * indicates that the type of key maintained by this map is character. The type of this mapping value is linkedlist<character> graph * means that the mapping relationship is stored in graph this map * linkedlist<character> Indicates that the element type in this collection is Character * * hashmap<character,integer> dist This HashMap is used to store each node and distance from the vertex s of the mapping relationship * Indicates that the type of the key maintained by this map is character the type of the value maintained by this mapping is integer. Dist indicates that the mapping relationship is stored in dist this mapping */private void BFs (Hashmap<character, linkedlist<character>> graph,hashmap< Character, Integer> Dist, char start) {//queue<character> indicates that the type of element saved in this collection is characterqueue< character> q = new linkedlist<character> (), Q.add (start),//inserts the specified element s into the queue, returns true on success, assuming no free space. Returns the Illegalstateexception//put (start,0) Start key that the specified value will be associated with, and 0 is the value that the specified value will be associated with. Assuming that starThe mapping relationship between T and 0 already exists, then the old value is returned and replaced 0//assuming that the mapping relationship between start and 0 does not exist, then return Nulldist.put (Start, 0); int i = 0;while (!q.isempty ())//{char top = Q.poll ( );//Gets and removes the header of the queue, returning the header of the queue, assuming the queue is empty. Returns nulli++;//Dist.get (top) returns the value mapped by the specified key top System.out.println ("the" + i + "th element:" + top+ "Distance from S-is:" + dist . Get (top)); int d = dist.get (top) + 1;//The distance of the nodes that have not been interviewed by the perimeter/* Graph.get (top) Assume that this mapping includes a meet (Key==null? K==null:key.equals (k )) * The mapping relationship from the K key to the V value, this method returns V; otherwise null is returned. (There can be only one such mapping relationship.)

* FOR (element variable: element collection), this loop is ended if all elements in the element collection have been traversed. Otherwise, run the program block */for (Character c:graph.get (top)) {//ContainsKey (key) in the For loop, assuming that this mapping includes a mapping relationship for the specified key key, then return Trueif (! Dist.containskey (c))//Assume that the element description in dist has not yet been interviewed {//association specifies the key C with the specified value D. Suppose the association relationship already exists. Replace the old value D. Returns the old value D, assuming no mapping relationship, returns Nulldist.put (C, D); Q.add (c); Inserts the specified element C into the queue, returning true when successful. Assuming there is no free space, return illegalstateexception}}}}private static void Dfs (Hashmap<character, linkedlist<character>> Graph,hashmap<character, Boolean> visited) {visit (graph, visited, ' s ');} private static void Visit (Hashmap<character, linkedlist<character>> graph,hashmap<character, Boolean > Visited,char start) {if (!visited.containskey (start)) {count++; System.out.println ("The time into element" + Start + ":" + count);//Record Visited.put (Start, true) on the node, for (Character C : Graph.get (Start)) {if (!visited.containskey (c)) {Visit (graph, visited, c);//recursive access to its neighboring node}}count++; System.out.println ("The Time Out element" + Start + ":" + count);//Record the duration of leaving the node}}public static void MaiN (String args[]) {BFS BB = new BFS ();//s Vertex adjacency table linkedlist<character> list_s = new linkedlist<character> (); Lis T_s.add (' W '); List_s.add (' R '); linkedlist<character> list_w = new linkedlist<character> () list_w.add (' s '); List_w.add (' x '); List_w.add ( ' I '); linkedlist<character> List_r = new linkedlist<character> (); List_r.add (' s '); List_r.add (' V '); linkedlist<character> list_x = new linkedlist<character> () List_x.add (' W '); List_x.add (' Y '); List_x.add ( ' U '); linkedlist<character> list_v = new linkedlist<character> (); List_v.add (' R '); linkedlist<character> list_i = new linkedlist<character> (); List_i.add (' W '); linkedlist<character> List_u = new linkedlist<character> (); List_u.add (' X '); linkedlist<character> list_y = new linkedlist<character> (); List_y.add (' X '); Hashmap<character, linkedlist<character>> graph = new Hashmap<character, linkedlist<character> > (); graph.put (' s ', list_s); Graph.put (' W ', lIST_W); Graph.put (' R ', List_r); Graph.put (' x ', list_x); Graph.put (' V ', list_v); Graph.put (' I ', list_i); Graph.put (' Y ', list_y); Graph.put (' U ', List_u); System.out.println ("BFS starts:"); Hashmap<character, integer> dist = new Hashmap<character, integer> (); char start = ' s '; bb.bfs (graph, Dist, STA RT); System.out.println ("DFS starts:"); Hashmap<character, boolean> visited=new hashmap<character, boolean> (); Bb.dfs (graph, visited);}}



The Java implementation of BFS and DFS

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.