Skip to content

Commit 1f2788d

Browse files
committed
feat: add 1042's answer
1 parent 1d9583d commit 1f2788d

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

1001-1100/1042. Flower Planting With No Adjacent.md

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,40 @@ Output: [1,2,3,4]
6363
## Solution
6464

6565
```javascript
66-
66+
/**
67+
* @param {number} n
68+
* @param {number[][]} paths
69+
* @return {number[]}
70+
*/
71+
var gardenNoAdj = function(n, paths) {
72+
var pathMap = Array(n).fill(0).map(() => ({}));
73+
for (var i = 0; i < paths.length; i++) {
74+
pathMap[paths[i][0] - 1][paths[i][1] - 1] = true;
75+
pathMap[paths[i][1] - 1][paths[i][0] - 1] = true;
76+
}
77+
var possibleMap = Array(n).fill(0).map(() => [1,1,1,1]);
78+
var result = Array(n).fill(0);
79+
for (var j = 0; j < n; j++) {
80+
var type = possibleMap[j].findIndex(item => item === 1);
81+
var others = Object.keys(pathMap[j]);
82+
for (var k = 0; k < others.length; k++) {
83+
possibleMap[others[k]][type] = 0;
84+
}
85+
result[j] = type + 1;
86+
}
87+
return result;
88+
};
6789
```
6890

6991
**Explain:**
7092

71-
nope.
93+
In the beginning, every garden can plant 4 types of flower.
94+
95+
We go through the gardens, pick one flower type from all passible choices for that garden.
96+
97+
And remove this kind of flower type from the possible types of all neighbor gardens.
98+
99+
In the end, you will have (one of) the result.
72100

73101
**Complexity:**
74102

0 commit comments

Comments
 (0)