Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package praktikum9;
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.Scanner;
- public class GraphTraversal {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- // Input jumlah Vertex
- System.out.print("Masukkan jumlah vertex: ");
- int jumlahVertex = sc.nextInt();
- // Inisialisasi Adjacency List
- LinkedList<Integer>[] adjacencyList = new LinkedList[jumlahVertex + 1];
- for (int i = 0; i < jumlahVertex + 1; i++) {
- adjacencyList[i] = new LinkedList<Integer>();
- }
- // Input jumlah Edge
- System.out.print("Masukkan jumlah edge: ");
- int jumlahEdge = sc.nextInt();
- // Input daftar Edge
- for (int i = 0; i < jumlahEdge; i++) {
- System.out.print("Masukkan edge ke-" + (i + 1) + ": ");
- int a = sc.nextInt();
- int b = sc.nextInt();
- adjacencyList[a].add(b);
- }
- boolean[] visited = new boolean[jumlahVertex + 1];
- System.out.print("DFS: ");
- dfs(adjacencyList, 1, visited);
- visited = new boolean[jumlahVertex + 1];
- System.out.print("\nBFS: ");
- bfs(adjacencyList, 1, visited);
- }
- public static void dfs(LinkedList<Integer>[] list, int current, boolean[] visited) {
- if (visited[current] == false) {
- visited[current] = true;
- System.out.print(current + " ");
- for (int i = 0; i < list[current].size(); i++) {
- dfs(list, list[current].get(i), visited);
- }
- }
- }
- public static void bfs(LinkedList<Integer>[] list, int current, boolean[] visited) {
- Queue<Integer> queue = new LinkedList<>();
- queue.add(current);
- while (!queue.isEmpty()) {
- int data = queue.remove();
- System.out.print(data + " ");
- for (int i = 0; i < list[data].size(); i++) {
- int neighbor = list[data].get(i);
- if (!visited[neighbor]) {
- visited[neighbor] = true;
- queue.add(neighbor);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement