Breadth First Search: Shortest Reach

  • + 0 comments

    Java 15:

    public static List<Integer> bfs(
        int n, int m, List<List<Integer>> edges, int s) {
      List<List<Integer>> graph = new ArrayList<>();
      List<Integer> distances = new ArrayList<>();
    
      for (int i = 0; i <= n; i++) {
        graph.add(new ArrayList<>());
      }
    
      for (List<Integer> edge : edges) {
        graph.get(edge.get(0)).add(edge.get(1));
        graph.get(edge.get(1)).add(edge.get(0));
      }
    
      int[] dist = bfsExplore(n, s, graph);
      System.out.println(Arrays.toString(dist));
      for (int i = 1; i <= n; i++) {
        if (i != s) {
          distances.add(dist[i]);
        }
      }
      return distances;
    }
    
    private static int[] bfsExplore(int n, int s, List<List<Integer>> graph) {
      int weight = 6;
      int[] distances = new int[n + 1];
      Arrays.fill(distances, -1);
      boolean[] visited = new boolean[n + 1];
      Queue<int[]> queue = new LinkedList<>();
      queue.offer(new int[] {s, 0});
      visited[s] = true;
    
      while (!queue.isEmpty()) {
        int[] current = queue.poll();
        distances[current[0]] = weight * current[1];
    
        for (int neighbor : graph.get(current[0])) {
          if (!visited[neighbor]) {
            queue.offer(new int[] {neighbor, current[1] + 1});
            visited[neighbor] = true;
          }
        }
      }
      return distances;
    }