|
| 1 | +/** |
| 2 | + * 1042. Flower Planting With No Adjacent |
| 3 | + * https://leetcode.com/problems/flower-planting-with-no-adjacent/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes |
| 7 | + * a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of |
| 8 | + * 4 types of flowers. |
| 9 | + * |
| 10 | + * All gardens have at most 3 paths coming into or leaving it. |
| 11 | + * |
| 12 | + * Your task is to choose a flower type for each garden such that, for any two gardens connected |
| 13 | + * by a path, they have different types of flowers. |
| 14 | + * |
| 15 | + * Return any such a choice as an array answer, where answer[i] is the type of flower planted in |
| 16 | + * the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer |
| 17 | + * exists. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number} n |
| 22 | + * @param {number[][]} paths |
| 23 | + * @return {number[]} |
| 24 | + */ |
| 25 | +var gardenNoAdj = function(n, paths) { |
| 26 | + const graph = Array.from({ length: n }, () => new Set()); |
| 27 | + const result = new Array(n).fill(0); |
| 28 | + |
| 29 | + for (const [x, y] of paths) { |
| 30 | + graph[x - 1].add(y - 1); |
| 31 | + graph[y - 1].add(x - 1); |
| 32 | + } |
| 33 | + |
| 34 | + for (let garden = 0; garden < n; garden++) { |
| 35 | + const usedColors = new Set(); |
| 36 | + for (const neighbor of graph[garden]) { |
| 37 | + usedColors.add(result[neighbor]); |
| 38 | + } |
| 39 | + |
| 40 | + for (let color = 1; color <= 4; color++) { |
| 41 | + if (!usedColors.has(color)) { |
| 42 | + result[garden] = color; |
| 43 | + break; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return result; |
| 49 | +}; |
0 commit comments