Advertisement
karbaev

bfs

Oct 26th, 2016
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1. package algo;
  2.  
  3. import java.util.*;
  4. import java.util.zip.Inflater;
  5.  
  6. /**
  7.  * Created by Danila on 26.10.2016.
  8.  */
  9. public class bfs {
  10.     static int[][] adjmatrix = {{0, 1, 0, 1}, {0, 0, 1, 1}, {0, 1, 0, 0}, {1, 0, 1, 0} };
  11.  
  12.     static Map<Integer,ArrayList<Integer>> adjMap = new HashMap<Integer, ArrayList<Integer>>();
  13.  
  14.     public static void fillEdges(){
  15.  
  16.         int adjCnt=1;
  17.         for(int i=0; i<adjmatrix.length;i++) {
  18.             ArrayList<Integer> curr = new ArrayList<>();
  19.             for (int j = 0; j < adjmatrix[0].length; j++) {
  20.                 if (adjmatrix[i][j] != 0) {
  21.                     curr.add(j+1);
  22.                 }
  23.             }
  24.             adjMap.put(adjCnt++, curr);
  25.         }
  26.     }
  27.  
  28.     public static void printAdjMap(){
  29.         for(int i=0; i<adjMap.size(); i++){
  30.             System.out.println("Node "+i+": ");
  31.             for(int x : adjMap.get(i)){
  32.                 System.out.print(x+" ");
  33.             }
  34.         }
  35.     }
  36.  
  37.     public static void bfs(){
  38.         Map<Integer, Integer> d = new HashMap<>();
  39.         Map<Integer, Boolean> mark = new HashMap<>();
  40.         int start = 1;
  41.         Queue<Integer> q = new LinkedList<Integer>();
  42.         q.add(start);
  43.         d.put(start, 0);
  44.         mark.put(start, true);
  45.         while(!q.isEmpty()){
  46.             int v = q.peek();
  47.             q.remove();
  48.             for(int i=0; i<adjMap.get(v).size(); i++){
  49.                 int current=adjMap.get(v).get(i);
  50.                 if(!mark.containsKey(current))
  51.                     mark.put(current,false);
  52.                 if(!mark.get(current)){
  53.                     if(d.containsKey(current)){
  54.                         d.replace(current, d.get(v)+1);
  55.                     }
  56.                     else d.put(current, d.get(v)+1);
  57.                     mark.replace(current, true);
  58.                     q.add(current);
  59.                 }
  60.             }
  61.         }
  62.         System.out.println(d);
  63.         System.out.println(mark);
  64.     }
  65.  
  66.     public static void main(String[] args) {
  67.         fillEdges();
  68.         System.out.println(adjMap);
  69.         bfs();
  70.     }
  71.  
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement