|
| 1 | +export const degreesOfSeparation = ( |
| 2 | + familyTree: Record<string, string[]>, |
| 3 | + personA: string, |
| 4 | + personB: string |
| 5 | +) => { |
| 6 | + const neighbors = new Map<string, Set<string>>() |
| 7 | + |
| 8 | + // Build adjacency list |
| 9 | + for (const [parent, children] of Object.entries(familyTree)) { |
| 10 | + const parentNeighbors = neighbors.get(parent) ?? new Set() |
| 11 | + neighbors.set(parent, parentNeighbors) |
| 12 | + |
| 13 | + for (const child of children) { |
| 14 | + const childNeighbors = neighbors.get(child) ?? new Set() |
| 15 | + neighbors.set(child, childNeighbors) |
| 16 | + |
| 17 | + parentNeighbors.add(child) |
| 18 | + childNeighbors.add(parent) |
| 19 | + |
| 20 | + // Connect siblings |
| 21 | + for (const sibling of children) { |
| 22 | + if (child !== sibling) { |
| 23 | + childNeighbors.add(sibling) |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + if (!neighbors.has(personA) || !neighbors.has(personB)) return -1 |
| 30 | + |
| 31 | + // BFS setup |
| 32 | + const queue: [string, number][] = [[personA, 0]] |
| 33 | + const visited = new Set([personA]) |
| 34 | + |
| 35 | + while (queue.length > 0) { |
| 36 | + const [current, degree] = queue.shift()! |
| 37 | + |
| 38 | + if (current === personB) return degree |
| 39 | + |
| 40 | + for (const neighbor of neighbors.get(current)!) { |
| 41 | + if (!visited.has(neighbor)) { |
| 42 | + visited.add(neighbor) |
| 43 | + queue.push([neighbor, degree + 1]) |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return -1 |
| 49 | +} |
0 commit comments