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, then accessing its connection point, A, B, and then accessing the connection table of a, it is natural that this data structure is hashmap, with vertex key, the connection table for each vertex is saved */public class BFS {static int count=0;/* * Hashmap<character,linkedlist<character>> Graph This HashMap is used to store the adjacency table for 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 hold 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, which represents the storage of the mapping relationship to dist This mapping */private void BFs (Hashmap<character, Linkedlist<character>> Graph,hashmap<character, Integer> Dist, char start) {//Queue<character> Indicates the type of the 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 if there is no free space, returns Illegalstateexception//put (start,0) Start the key to which the specified value will be associated, and 0 is the value to which the specified value will be associated, if start and 0The mapping relationship already exists, and the old value is returned and replaced 0//if 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, returns the header of the queue if 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+ "Dis Tance from S is: "+ dist.get (top)"), int d = dist.get (top) + 1;//the distance from the node to which the perimeter has not been accessed */* Graph.get (top) If this mapping contains a satisfy (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 at most one such mapping relationship.) * FOR (element variable: element collection), if all elements in the element collection have been traversed, end this loop, otherwise execute the block */for (Character c:graph.get (top)) {//ContainsKey (key) The shot contains a mapping relationship to the specified key, which returns Trueif (!dist.containskey (c))//If the element description has not been accessed in Dist (//association specified key C with the specified value D, if the association relationship already exists, replace the old value D, return the old value D, If there is no mapping relationship, return Nulldist.put (c, D); Q.add (c); Inserts the specified element C into the queue, returns true on success, and returns illegalstateexception}}}}private static void Dfs (Hashmap<character, if no free space is available). Linkedlist<character>> Graph,hashmap<character, Boolean> visited) {visit (graph, visited, ' s ');} private static void Visit (Hashmap<character, LINKEDLIST&LT 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);//recursively accesses its neighboring nodes}}count++; System.out.println ("The Time Out element" + Start + ":" + count);//Record the duration of the departure of the node}}public static void Main (String args[]) {B FS BB = new BFS ();//s Vertex adjacency table linkedlist<character> list_s = new linkedlist<character> (); List_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);}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.