Statement
Solution
Naive approach
A naive approach for finding cycles of length in a given set of rooms is based on DFS traversal. We apply DFS on a room and traverse until we visit its neighbors up to a depth of . If the next neighbor is the source room, we have found a cycle of length . Otherwise, we have not. Repeat this process for all the other rooms, and count all the cycles of length 3.
The time complexity for DFS traversal on a single node is , where represents the number of vertices and represents the number of edges in the graph. Since we perform DFS traversal on every node in the graph, the overall time complexity can be expressed as . However, the space complexity of this approach is .
Optimized approach using graph algo
We solve this problem using the adjacency list. We initialize a dictionary, neighbors
, containing all rooms as keys and their neighboring rooms as corresponding values. Since corridors[i]=[room1,room2]
represents a corridor showing that the two rooms are connected, we update the adjacency list as neighbors[room1] = room2
and neighbors[room2] = room1
.
While updating neighbors
with the corridor , we know that and are directly connected. After updating neighbors
with this corridor, we can look for any common room that exists in both neighbors[room1]
and neighbors[room2]
. This can be done by taking the intersection of neighbors[room1]
and neighbors[room2]
. If we find any common room, say , we conclude that is connected to both and . Therefore, we come to know that , , and are connected with each other, forming a cycle of length .
Let’s look at the following illustration to get a better understanding of the solution: