|
| 1 | +/** |
| 2 | + * 2493. Divide Nodes Into the Maximum Number of Groups |
| 3 | + * https://leetcode.com/problems/divide-nodes-into-the-maximum-number-of-groups/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a positive integer n representing the number of nodes in an undirected graph. |
| 7 | + * The nodes are labeled from 1 to n. |
| 8 | + * |
| 9 | + * You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there |
| 10 | + * is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected. |
| 11 | + * |
| 12 | + * Divide the nodes of the graph into m groups (1-indexed) such that: |
| 13 | + * - Each node in the graph belongs to exactly one group. |
| 14 | + * - For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to |
| 15 | + * the group with index x, and bi belongs to the group with index y, then |y - x| = 1. |
| 16 | + * |
| 17 | + * Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. |
| 18 | + * Return -1 if it is impossible to group the nodes with the given conditions. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number} n |
| 23 | + * @param {number[][]} edges |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var magnificentSets = function(n, edges) { |
| 27 | + const graph = new Array(n).fill().map(() => []); |
| 28 | + for (const [i, j] of edges) { |
| 29 | + graph[i - 1].push(j - 1); |
| 30 | + graph[j - 1].push(i - 1); |
| 31 | + } |
| 32 | + |
| 33 | + const result = new Array(n).fill(0); |
| 34 | + for (let i = 0; i < n; i++) { |
| 35 | + const groups = new Array(n).fill(0); |
| 36 | + const queue = [i]; |
| 37 | + let max = 1; |
| 38 | + let root = i; |
| 39 | + |
| 40 | + groups[i] = 1; |
| 41 | + |
| 42 | + while (queue.length) { |
| 43 | + const key = queue.shift(); |
| 44 | + root = Math.min(root, key); |
| 45 | + |
| 46 | + for (const node of graph[key]) { |
| 47 | + if (groups[node] === 0) { |
| 48 | + groups[node] = groups[key] + 1; |
| 49 | + max = Math.max(max, groups[node]); |
| 50 | + queue.push(node); |
| 51 | + } else if (Math.abs(groups[node] - groups[key]) !== 1) { |
| 52 | + return -1; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + result[root] = Math.max(result[root], max); |
| 58 | + } |
| 59 | + |
| 60 | + return result.reduce((a, b) => a + b); |
| 61 | +}; |
0 commit comments