Paths in Maze That Lead to Same Room - Problem

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] = [room1i, room2i] indicates that there is a corridor connecting room1i and room2i, allowing a person in the maze to go from room1i to room2i 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 → 1 is a cycle of length 3, but 1 → 2 → 3 → 4 and 1 → 2 → 3 → 2 → 1 are 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.

Input & Output

Example 1 — Basic Triangle
$ Input: n = 5, corridors = [[1,2],[2,3],[3,1]]
Output: 1
💡 Note: There is exactly one cycle of length 3: 1 → 2 → 3 → 1. Rooms 4 and 5 are isolated and don't form any cycles.
Example 2 — Multiple Triangles
$ Input: n = 4, corridors = [[1,2],[2,3],[3,4],[4,1],[1,3]]
Output: 2
💡 Note: There are exactly two cycles of length 3: 1 → 2 → 3 → 1 and 1 → 3 → 4 → 1. The corridor [1,3] participates in both triangles.
Example 3 — No Triangles
$ Input: n = 4, corridors = [[1,2],[2,3],[3,4]]
Output: 0
💡 Note: This forms a simple path 1-2-3-4 with no cycles of length 3. All paths are longer than 3 or are not cycles.

Constraints

  • 3 ≤ n ≤ 1000
  • 0 ≤ corridors.length ≤ n × (n-1) / 2
  • corridors[i].length == 2
  • 1 ≤ room1i, room2i ≤ n
  • room1i ≠ room2i
  • There are no duplicate corridors

Visualization

Tap to expand
Paths in Maze - Cycle Detection INPUT Graph with n=5 rooms 1 2 3 4 5 corridors: [1,2] [2,3] [3,1] n = 5 rooms 3 corridors (edges) ALGORITHM STEPS 1 Build Adjacency List Store neighbors for each node 1: [2,3] 2: [1,3] 3: [1,2] 2 For each edge (u,v) Check common neighbors 3 Find Common Neighbors w in adj[u] AND adj[v] 1 2 3 Triangle Found! 4 Count Triangles Each triangle counted once FINAL RESULT Cycle of Length 3 Found: 1 2 3 1 --> 2 --> 3 --> 1 Confusion Score 1 OK - 1 triangle detected Rooms 4,5 not in any cycle Key Insight: Adjacency List Optimization: For each edge (u,v), find common neighbors w that form triangles. A cycle of length 3 exists when three rooms are mutually connected (forming a triangle in the graph). Time Complexity: O(E * sqrt(E)) using sorted adjacency lists. Count intersection of neighbor sets. TutorialsPoint - Paths in Maze That Lead to Same Room | Adjacency List Optimization
Asked in
Facebook 15 Google 12 Microsoft 8
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen