Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package algo;
- import java.util.*;
- import java.util.zip.Inflater;
- /**
- * Created by Danila on 26.10.2016.
- */
- public class bfs {
- static int[][] adjmatrix = {{0, 1, 0, 1}, {0, 0, 1, 1}, {0, 1, 0, 0}, {1, 0, 1, 0} };
- static Map<Integer,ArrayList<Integer>> adjMap = new HashMap<Integer, ArrayList<Integer>>();
- public static void fillEdges(){
- int adjCnt=1;
- for(int i=0; i<adjmatrix.length;i++) {
- ArrayList<Integer> curr = new ArrayList<>();
- for (int j = 0; j < adjmatrix[0].length; j++) {
- if (adjmatrix[i][j] != 0) {
- curr.add(j+1);
- }
- }
- adjMap.put(adjCnt++, curr);
- }
- }
- public static void printAdjMap(){
- for(int i=0; i<adjMap.size(); i++){
- System.out.println("Node "+i+": ");
- for(int x : adjMap.get(i)){
- System.out.print(x+" ");
- }
- }
- }
- public static void bfs(){
- Map<Integer, Integer> d = new HashMap<>();
- Map<Integer, Boolean> mark = new HashMap<>();
- int start = 1;
- Queue<Integer> q = new LinkedList<Integer>();
- q.add(start);
- d.put(start, 0);
- mark.put(start, true);
- while(!q.isEmpty()){
- int v = q.peek();
- q.remove();
- for(int i=0; i<adjMap.get(v).size(); i++){
- int current=adjMap.get(v).get(i);
- if(!mark.containsKey(current))
- mark.put(current,false);
- if(!mark.get(current)){
- if(d.containsKey(current)){
- d.replace(current, d.get(v)+1);
- }
- else d.put(current, d.get(v)+1);
- mark.replace(current, true);
- q.add(current);
- }
- }
- }
- System.out.println(d);
- System.out.println(mark);
- }
- public static void main(String[] args) {
- fillEdges();
- System.out.println(adjMap);
- bfs();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement