Problem Description
Given an undirected graph representing a maze with n rooms and corridors between them, determine the confusion score defined as the number of unique cycles of exactly length 3 (triangles) in the graph.
Key Insights
- The problem reduces to counting the number of triangles in an undirected graph.
- Each triangle (cycle of length 3) will be counted three times if iterating over all edges, so the final count must be divided by 3.
- Use an adjacency list (with sets) to efficiently check whether two nodes have a common neighbor.
- Iterating over each corridor and computing the intersection of neighbors enables fast counting of triangles.
Space and Time Complexity
Time Complexity: O(E * min(deg(u), deg(v))) where E is the number of corridors; in worst-case scenarios this is efficient given the constraints. Space Complexity: O(n + E) for storing the adjacency list.
Solution
We use an adjacency list (using sets for quick membership tests) to represent the graph. For each corridor (edge) connecting two rooms, we find the intersection of the neighbor sets of the two rooms (this gives common neighbors that can close a triangle). The sum of all intersections gives three times the number of triangles (since each triangle gets counted at each of its three edges), so we divide the total count by 3 to get the final answer.