Advertisement
MonsterScripter

CodinGame_2023_09_13__16_42_56__TestDFS.java

Sep 13th, 2023
1,030
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class TestDFS {
  4.     public static void main(String args[]) {
  5.  
  6.         Graph graph = new Graph(7);
  7.         graph.addEdge(0, 1);
  8.         graph.addEdge(0, 2);
  9.         graph.addEdge(1, 3);
  10.         graph.addEdge(1, 4);
  11.         graph.addEdge(2, 5);
  12.         graph.addEdge(2, 6);
  13.  
  14.         List<Integer> result = graph.dfs(0);
  15.         System.out.println(result); // Expected output: [0, 1, 3, 4, 2, 5, 6]
  16.     }
  17.  
  18.     private static class Graph {
  19.         private int V; // Number of nodes (vertices) in the graph
  20.         private LinkedList<Integer>[] adjacency; // Adjacency list
  21.  
  22.         @SuppressWarnings("unchecked")
  23.         public Graph(int v) {
  24.             V = v;
  25.             adjacency = new LinkedList[v];
  26.             for (int i = 0; i < v; ++i) {
  27.                 adjacency[i] = new LinkedList<>();
  28.             }
  29.         }
  30.  
  31.         // Add an edge between nodes u and v
  32.         public void addEdge(int u, int v) {
  33.             adjacency[u].add(v);
  34.             adjacency[v].add(u); // The graph is undirected
  35.         }
  36.  
  37.         // Recursive function to perform DFS from a given node
  38.         private void dfsRecursive(int n, boolean[] visited, List<Integer> result) {
  39.             visited[n] = true;
  40.             result.add(n);
  41.  
  42.             // Traverse all unvisited adjacent nodes
  43.             for (Integer neighbor : adjacency[n]) {
  44.                 if (!visited[neighbor]) {
  45.                     dfsRecursive(neighbor, visited, result);
  46.                 }
  47.             }
  48.         }
  49.  
  50.         // Perform Depth-First Search (DFS) from the given node and return the order of visit
  51.         public List<Integer> dfs(int n) {
  52.             boolean[] visited = new boolean[V]; // Array to track visited nodes
  53.             List<Integer> result = new ArrayList<>(); // List to store the order of visit
  54.  
  55.             dfsRecursive(n, visited, result); // Call the recursive DFS function
  56.  
  57.             return result;
  58.         }
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement