DSA Graphs

Paths in Maze That Lead to Same Room

Count triangles in an undirected graph — for each edge (u, v), count neighbors shared by both, then divide.

Medium
Time O(V * E / 32) Space O(V * V / 8)
4 min read
graph bitset triangle-count

Problem#

An curriculum-track problem. Given an undirected graph of n rooms and a list of corridors, count the number of length-3 cycles (triangles) — sets of three rooms pairwise connected.

Examples#

  • n = 5, corridors = [[1,2],[5,2],[4,1],[2,4],[3,1],[3,4]]2
  • n = 4, corridors = [[1,2],[3,4]]0

Constraints#

  • 2 <= n <= 1000, 1 <= corridors.length <= 5 * 10^4.

Approach#

For each edge (u, v), the number of triangles containing it equals the number of common neighbors. Use bitset adjacency to compute the intersection size in O(n / 64). Sum across all edges, divide by 3 (each triangle is counted by each of its three edges).

Solution#

Paths in Maze That Lead to Same Room
class Solution {
public:
int numberOfPaths(int n, vector<vector<int>>& corridors) {
vector<bitset<1001>> adj(n + 1);
for (auto& c : corridors) {
adj[c[0]].set(c[1]);
adj[c[1]].set(c[0]);
}
long long total = 0;
for (auto& c : corridors) {
total += (adj[c[0]] & adj[c[1]]).count();
}
return (int)(total / 3);
}
};

Editorial#

For each edge (u, v), common neighbors of u and v complete a triangle (u, v, w). The bitset AND gives the count of such w in O(n / word_size). Each triangle’s three edges each contribute the same triangle once, hence the division by 3.

Complexity#

  • Time: O(V * E / 64).
  • Space: O(V^2 / 8).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.