Advertisement
Yesver08

GraphTraversal.java

Nov 19th, 2021
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.19 KB | None | 0 0
  1. package praktikum9;
  2.  
  3. import java.util.LinkedList;
  4. import java.util.Queue;
  5. import java.util.Scanner;
  6.  
  7. public class GraphTraversal {
  8.     public static void main(String[] args) {
  9.         Scanner sc = new Scanner(System.in);
  10.  
  11.         // Input jumlah Vertex
  12.         System.out.print("Masukkan jumlah vertex: ");
  13.         int jumlahVertex = sc.nextInt();
  14.  
  15.         // Inisialisasi Adjacency List
  16.         LinkedList<Integer>[] adjacencyList = new LinkedList[jumlahVertex + 1];
  17.         for (int i = 0; i < jumlahVertex + 1; i++) {
  18.             adjacencyList[i] = new LinkedList<Integer>();
  19.         }
  20.  
  21.         // Input jumlah Edge
  22.         System.out.print("Masukkan jumlah edge: ");
  23.         int jumlahEdge = sc.nextInt();
  24.  
  25.         // Input daftar Edge
  26.         for (int i = 0; i < jumlahEdge; i++) {
  27.             System.out.print("Masukkan edge ke-" + (i + 1) + ": ");
  28.             int a = sc.nextInt();
  29.             int b = sc.nextInt();
  30.             adjacencyList[a].add(b);
  31.         }
  32.  
  33.         boolean[] visited = new boolean[jumlahVertex + 1];
  34.         System.out.print("DFS: ");
  35.         dfs(adjacencyList, 1, visited);
  36.         visited = new boolean[jumlahVertex + 1];
  37.         System.out.print("\nBFS: ");
  38.         bfs(adjacencyList, 1, visited);
  39.     }
  40.  
  41.     public static void dfs(LinkedList<Integer>[] list, int current, boolean[] visited) {
  42.         if (visited[current] == false) {
  43.             visited[current] = true;
  44.             System.out.print(current + " ");
  45.             for (int i = 0; i < list[current].size(); i++) {
  46.                 dfs(list, list[current].get(i), visited);
  47.             }
  48.         }
  49.     }
  50.  
  51.     public static void bfs(LinkedList<Integer>[] list, int current, boolean[] visited) {
  52.         Queue<Integer> queue = new LinkedList<>();
  53.         queue.add(current);
  54.  
  55.         while (!queue.isEmpty()) {
  56.             int data = queue.remove();
  57.             System.out.print(data + " ");
  58.  
  59.             for (int i = 0; i < list[data].size(); i++) {
  60.                 int neighbor = list[data].get(i);
  61.                 if (!visited[neighbor]) {
  62.                     visited[neighbor] = true;
  63.                     queue.add(neighbor);
  64.                 }
  65.             }
  66.         }
  67.     }
  68.  
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement