1042. Flower Planting With No Adjacent

```java
class Solution {
    public int[] gardenNoAdj(int n, int[][] paths) {
        int[] result = new int[n];
        Arrays.fill(result, 1); // draw one color first

        boolean stop = false;
        while (!stop) {
            stop = true;
            for (int[] path : paths) {
                int u = Math.min(path[0]-1, path[1]-1);
                int v = Math.max(path[0]-1, path[1]-1);

                if (result[u] == result[v]) { // same pattern to change color
                    stop = false;
                    result[u] = getNextColor(result[v]);
                }
            }
        }
        return result;
    }
    private int getNextColor(int c) {
        return c == 4 ? 1 : c+1;
    }
}

```

use set

result is the color we used for result, so when we deal this next node, we can exclude the color we used before.

Last updated

Was this helpful?