Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Main {
- static final int MAX = 1000;
- static List<Integer>[] adj = (List<Integer>[]) new ArrayList[MAX];
- /* নিচের মত হচ্ছেনা তাই উপরে arrayList এর array ব্যবহার করেছি । declaration এ কোন প্রবলেম নাই */
- // static List<List<Integer>> adj = new ArrayList<List<Integer>>(MAX);
- static int[] distance = new int[MAX];
- static int[] visited = new int[MAX];
- static Queue<Integer> q = new LinkedList<Integer>();
- static void BFS(int source){
- q.add(source);
- distance[source] = 0;
- visited[source] = 1;
- System.out.println("Level " + distance[source] + " : " + source);
- while (!q.isEmpty()) {
- int pop = q.peek();
- int temp;
- for (int i = 0; i < adj[pop].size(); i++) {
- temp = adj[pop].get(i);
- if (visited[temp] == 0) {
- distance[temp] = distance[pop] + 1;
- visited[temp] = 1;
- q.add(temp);
- System.out.println("Level " + distance[temp] + " : " + temp);
- }
- }
- q.remove();
- }
- }
- public static void main(String[] args) {
- int edge, u, v, source;
- Scanner input = new Scanner(System.in);
- edge = input.nextInt();
- for (int i = 0; i < edge; i++) {
- u = input.nextInt();
- v = input.nextInt();
- if (adj[v]==null) adj[v] = new ArrayList<Integer>();
- adj[v].add(u);
- if (adj[u]==null) adj[u] = new ArrayList<Integer>();
- adj[u].add(v);
- /* এইখানে প্রবলেম । রান করলে array out of bound exception দেখায় । stackOverFlow তে এইরকম একজন suggest করছিল */
- // adj.get(u).add(v);
- // adj.get(v).add(u);
- }
- source = input.nextInt();
- Arrays.fill(visited, 0);
- Arrays.fill(distance, 0);
- BFS(source);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment