Paths in Maze That Lead to Same Room Problem
Description
LeetCode Problem 2077.
A maze consists of n rooms numbered from 1 to n, and some rooms are connected by corridors. You are given a 2D integer array corridors where corridors[i] = [room1_i, room2_i] indicates that there is a corridor connecting room1_i and room2_i, allowing a person in the maze to go from room1_i to room2_i and vice versa.
The designer of the maze wants to know how confusing the maze is. The confusion score of the maze is the number of different cycles of length 3.
- For example,
1 → 2 → 3 → 1is a cycle of length 3, but1 → 2 → 3 → 4and1 → 2 → 3 → 2 → 1are not.
Two cycles are considered to be different if one or more of the rooms visited in the first cycle is not in the second cycle.
Return the confusion score of the maze.
Example 1:

Input: n = 5, corridors = [[1,2],[5,2],[4,1],[2,4],[3,1],[3,4]]
Output: 2
Explanation:
One cycle of length 3 is 4 → 1 → 3 → 4, denoted in red.
Note that this is the same cycle as 3 → 4 → 1 → 3 or 1 → 3 → 4 → 1 because the rooms are the same.
Another cycle of length 3 is 1 → 2 → 4 → 1, denoted in blue.
Thus, there are two different cycles of length 3.
Example 2:

Input: n = 4, corridors = [[1,2],[3,4]]
Output: 0
Explanation:
There are no cycles of length 3.
Constraints:
2 <= n <= 10001 <= corridors.length <= 5 * 10^4corridors[i].length == 21 <= room1_i, room2_i <= nroom1_i != room2_i- There are no duplicate corridors.
Solution
Approach: Count triangles with adjacency sets
A cycle of length 3 is a triangle, three rooms that are pairwise connected. Store each room's neighbours in a hash set so that "are these two rooms connected?" is a constant-time lookup.
For every room c, look at each unordered pair of its neighbours (a, b); if a and b are connected, then c, a, b form a triangle. Every triangle is found once from each of its three rooms, so divide the total by 3.
Complexity: O(sum of deg(v)^2) time, which is at most O(n * d^2) for maximum degree d; O(n + m) space for the adjacency sets.
from collections import defaultdict
from itertools import combinations
class Solution:
def numberOfPaths(self, n: int, corridors: List[List[int]]) -> int:
g = defaultdict(set)
for a, b in corridors:
g[a].add(b)
g[b].add(a)
ans = 0
for i in range(1, n + 1):
for j, k in combinations(g[i], 2):
if j in g[k]:
ans += 1
return ans // 3