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
Maze Confusion Score: Count 3-Room CyclesInput: Maze Corridors1234Process: Find TrianglesTriangle 1-2-3✓ All connectedPath 2-3-4✗ Not triangleOutput1triangle foundA 3-cycle creates confusion: 1→2→3→1 or 1→3→2→1Key: Check all room triplets for mutual connectionsConfusion Score = Number of Triangles = 1
Understanding the Visualization
1
Input Graph
Maze with rooms connected by corridors
2
Find Triangles
Identify cycles of exactly 3 rooms
3
Count Result
Return total number of distinct triangles
Key Takeaway
🎯 Key Insight: A triangle (3-cycle) exists when three rooms are all mutually connected - this creates maximum confusion as there are multiple valid paths between any two rooms in the triangle.
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