Skip to content

2204. Distance to a Cycle in Undirected Graph 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution {
 public:
  vector<int> distanceToCycle(int n, vector<vector<int>>& edges) {
    vector<int> ans(n);
    vector<vector<int>> graph(n);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      graph[u].push_back(v);
      graph[v].push_back(u);
    }

    // rank[i] := the minimum node that node i can reach with forward edges
    // Initialize with NO_RANK = -2 to indicate not visited.
    vector<int> cycle;
    getRank(graph, 0, 0, vector<int>(n, NO_RANK), cycle);

    queue<int> q;
    vector<bool> seen(n);
    for (const int u : cycle) {
      q.push(u);
      seen[u] = true;
    }

    for (int step = 1; !q.empty(); ++step)
      for (int sz = q.size(); sz > 0; --sz) {
        const int u = q.front();
        q.pop();
        for (const int v : graph[u]) {
          if (seen[v])
            continue;
          q.push(v);
          seen[v] = true;
          ans[v] = step;
        }
      }

    return ans;
  }

 private:
  static constexpr int NO_RANK = -2;

  // The minRank that u can reach with forward edges
  int getRank(const vector<vector<int>>& graph, int u, int currRank,
              vector<int>&& rank, vector<int>& cycle) {
    if (rank[u] != NO_RANK)  // The rank is already determined
      return rank[u];

    rank[u] = currRank;
    int minRank = currRank;

    for (const int v : graph[u]) {
      // Visited || parent (that's why NO_RANK = -2 instead of -1)
      if (rank[v] == rank.size() || rank[v] == currRank - 1)
        continue;
      const int nextRank =
          getRank(graph, v, currRank + 1, std::move(rank), cycle);
      // NextRank should > currRank if there's no cycle
      if (nextRank <= currRank)
        cycle.push_back(v);
      minRank = min(minRank, nextRank);
    }

    rank[u] = rank.size();  // Mark as visited.
    return minRank;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution {
  public int[] distanceToCycle(int n, int[][] edges) {
    int[] ans = new int[n];
    List<Integer>[] graph = new List[n];

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      graph[u].add(v);
      graph[v].add(u);
    }

    // rank[i] := the minimum node that node i can reach with forward edges
    // Initialize with NO_RANK = -2 to indicate not visited.
    int[] rank = new int[n];
    Arrays.fill(rank, NO_RANK);
    List<Integer> cycle = new ArrayList<>();
    getRank(graph, 0, 0, rank, cycle);

    Queue<Integer> q = cycle.stream().collect(Collectors.toCollection(ArrayDeque::new));
    boolean[] seen = new boolean[n];
    for (final int u : cycle)
      seen[u] = true;

    for (int step = 1; !q.isEmpty(); ++step)
      for (int sz = q.size(); sz > 0; --sz) {
        final int u = q.poll();
        for (final int v : graph[u]) {
          if (seen[v])
            continue;
          q.offer(v);
          seen[v] = true;
          ans[v] = step;
        }
      }

    return ans;
  }

  private static final int NO_RANK = -2;

  // The minRank that u can reach with forward edges
  private int getRank(List<Integer>[] graph, int u, int currRank, int[] rank, List<Integer> cycle) {
    if (rank[u] != NO_RANK) // The rank is already determined
      return rank[u];

    rank[u] = currRank;
    int minRank = currRank;

    for (final int v : graph[u]) {
      // Visited || parent (that's why NO_RANK = -2 instead of -1)
      if (rank[u] == rank.length || rank[v] == currRank - 1)
        continue;
      final int nextRank = getRank(graph, v, currRank + 1, rank, cycle);
      // NextRank should > currRank if there's no cycle
      if (nextRank <= currRank)
        cycle.add(v);
      minRank = Math.min(minRank, nextRank);
    }

    rank[u] = rank.length; // Mark as visited.
    return minRank;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution:
  def distanceToCycle(self, n: int, edges: list[list[int]]) -> list[int]:
    ans = [0] * n
    graph = [[] for _ in range(n)]

    for u, v in edges:
      graph[u].append(v)
      graph[v].append(u)

    NO_RANK = -2

    # The minRank that u can reach with forward edges
    def getRank(u: int, currRank: int, rank: list[int]) -> int:
      if rank[u] != NO_RANK:  # The rank is already determined
        return rank[u]

      rank[u] = currRank
      minRank = currRank

      for v in graph[u]:
        # Visited or parent (that's why NO_RANK = -2 instead of -1)
        if rank[v] == len(rank) or rank[v] == currRank - 1:
          continue
        nextRank = getRank(v, currRank + 1, rank)
        # NextRank should > currRank if there's no cycle
        if nextRank <= currRank:
          cycle.append(v)
        minRank = min(minRank, nextRank)

      rank[u] = len(rank)  # Mark as visited.
      return minRank

    # rank[i] := the minimum node that node i can reach with forward edges
    # Initialize with NO_RANK = -2 to indicate not visited.
    cycle = []
    getRank(0, 0, [NO_RANK] * n)

    q = collections.deque(cycle)
    seen = set(cycle)

    step = 1
    while q:
      for _ in range(len(q)):
        u = q.popleft()
        for v in graph[u]:
          if v in seen:
            continue
          q.append(v)
          seen.add(v)
          ans[v] = step
      step += 1

    return ans