|
| 1 | +/** |
| 2 | + * 2077. Paths in Maze That Lead to Same Room |
| 3 | + * https://leetcode.com/problems/paths-in-maze-that-lead-to-same-room/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A maze consists of n rooms numbered from 1 to n, and some rooms are connected by corridors. |
| 7 | + * You are given a 2D integer array corridors where corridors[i] = [room1i, room2i] indicates |
| 8 | + * that there is a corridor connecting room1i and room2i, allowing a person in the maze to go |
| 9 | + * from room1i to room2i and vice versa. |
| 10 | + * |
| 11 | + * The designer of the maze wants to know how confusing the maze is. The confusion score of |
| 12 | + * the maze is the number of different cycles of length 3. |
| 13 | + * - For example, 1 → 2 → 3 → 1 is a cycle of length 3, but 1 → 2 → 3 → 4 and |
| 14 | + * 1 → 2 → 3 → 2 → 1 are not. |
| 15 | + * |
| 16 | + * Two cycles are considered to be different if one or more of the rooms visited in the first |
| 17 | + * cycle is not in the second cycle. |
| 18 | + * |
| 19 | + * Return the confusion score of the maze. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} n |
| 24 | + * @param {number[][]} corridors |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var numberOfPaths = function(n, corridors) { |
| 28 | + const graph = Array.from({ length: n + 1 }, () => new Set()); |
| 29 | + |
| 30 | + for (const [room1, room2] of corridors) { |
| 31 | + graph[room1].add(room2); |
| 32 | + graph[room2].add(room1); |
| 33 | + } |
| 34 | + |
| 35 | + let cycles = 0; |
| 36 | + |
| 37 | + for (let i = 1; i <= n; i++) { |
| 38 | + const neighbors = Array.from(graph[i]); |
| 39 | + |
| 40 | + for (let j = 0; j < neighbors.length; j++) { |
| 41 | + for (let k = j + 1; k < neighbors.length; k++) { |
| 42 | + const neighbor1 = neighbors[j]; |
| 43 | + const neighbor2 = neighbors[k]; |
| 44 | + |
| 45 | + if (neighbor1 > i && neighbor2 > i && graph[neighbor1].has(neighbor2)) { |
| 46 | + cycles++; |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return cycles; |
| 53 | +}; |
0 commit comments