Skip to content

2608. Shortest Cycle in a Graph 👍

  • Time: $O(n^2)$
  • 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
class Solution {
 public:
  int findShortestCycle(int n, vector<vector<int>>& edges) {
    int ans = kInf;
    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);
    }

    for (int i = 0; i < n; ++i)
      ans = min(ans, bfs(graph, i));

    return ans == kInf ? -1 : ans;
  }

 private:
  static constexpr int kInf = 1001;

  // Returns the length of the minimum cycle by starting BFS from node `i`.
  // Returns `kInf` if there's no cycle.
  int bfs(const vector<vector<int>>& graph, int i) {
    vector<int> dist(graph.size(), kInf);
    queue<int> q{{i}};
    dist[i] = 0;
    while (!q.empty()) {
      const int u = q.front();
      q.pop();
      for (const int v : graph[u]) {
        if (dist[v] == kInf) {
          dist[v] = dist[u] + 1;
          q.push(v);
        } else if (dist[v] + 1 != dist[u]) {  // v is not a parent u.
          return dist[v] + dist[u] + 1;
        }
      }
    }
    return kInf;
  }
};
 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
class Solution {
  public int findShortestCycle(int n, int[][] edges) {
    int ans = kInf;
    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);
    }

    for (int i = 0; i < n; ++i)
      ans = Math.min(ans, bfs(graph, i));

    return ans == kInf ? -1 : ans;
  }

  private static final int kInf = 1001;

  // Returns the length of the minimum cycle by starting BFS from node `i`.
  // Returns `kInf` if there's no cycle.
  private int bfs(List<Integer>[] graph, int i) {
    int[] dist = new int[graph.length];
    Arrays.fill(dist, kInf);
    Queue<Integer> q = new ArrayDeque<>(List.of(i));
    dist[i] = 0;
    while (!q.isEmpty()) {
      final int u = q.poll();
      for (final int v : graph[u]) {
        if (dist[v] == kInf) {
          dist[v] = dist[u] + 1;
          q.offer(v);
        } else if (dist[v] + 1 != dist[u]) { // v is not a parent u.
          return dist[v] + dist[u] + 1;
        }
      }
    }
    return kInf;
  }
}
 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
class Solution:
  def findShortestCycle(self, n: int, edges: list[list[int]]) -> int:
    kInf = 1001
    ans = kInf
    graph = [[] for _ in range(n)]

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

    def bfs(i: int) -> int:
      """Returns the length of the minimum cycle by starting BFS from node `i`.

      Returns `kInf` if there's no cycle.
      """
      dist = [kInf] * n
      q = collections.deque([i])
      dist[i] = 0
      while q:
        u = q.popleft()
        for v in graph[u]:
          if dist[v] == kInf:
            dist[v] = dist[u] + 1
            q.append(v)
          elif dist[v] + 1 != dist[u]:   # v is not a parent u.
            return dist[v] + dist[u] + 1
      return kInf

    ans = min(map(bfs, range(n)))
    return -1 if ans == kInf else ans