Skip to content

1042. Flower Planting With No Adjacent

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
 public:
  vector<int> gardenNoAdj(int n, vector<vector<int>>& paths) {
    vector<int> ans(n);  // ans[i] := 1, 2, 3, or 4
    vector<vector<int>> graph(n);

    for (const vector<int>& path : paths) {
      const int u = path[0] - 1;
      const int v = path[1] - 1;
      graph[u].push_back(v);
      graph[v].push_back(u);
    }

    for (int u = 0; u < n; ++u) {
      int used = 0;
      for (const int v : graph[u])
        used |= 1 << ans[v];
      ans[u] = getFirstUnusedType(used);
    }

    return ans;
  }

 private:
  int getFirstUnusedType(int used) {
    for (int type = 1; type <= 4; ++type)
      if ((used >> type & 1) == 0)
        return type;
    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
  public int[] gardenNoAdj(int n, int[][] paths) {
    int[] ans = new int[n]; // ans[i] := 1, 2, 3, or 4
    List<Integer>[] graph = new List[n];

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] path : paths) {
      final int u = path[0] - 1;
      final int v = path[1] - 1;
      graph[u].add(v);
      graph[v].add(u);
    }

    for (int u = 0; u < n; ++u) {
      int used = 0;
      for (final int v : graph[u])
        used |= 1 << ans[v];
      ans[u] = getFirstUnusedType(used);
    }

    return ans;
  }

  private int getFirstUnusedType(int used) {
    for (int type = 1; type <= 4; ++type)
      if ((used >> type & 1) == 0)
        return type;
    throw new IllegalArgumentException();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def gardenNoAdj(self, n: int, paths: list[list[int]]) -> list[int]:
    ans = [0] * n  # ans[i] := 1, 2, 3, or 4
    graph = [[] for _ in range(n)]

    for x, y in paths:
      u = x - 1
      v = y - 1
      graph[u].append(v)
      graph[v].append(u)

    for u in range(n):
      used = functools.reduce(operator.or_, (1 << ans[v] for v in graph[u]), 0)
      ans[u] = next(type_
                    for type_ in range(1, 5)
                    if not (used >> type_ & 1))

    return ans