MediumDepth-First SearchBreadth-First SearchGraphGreedy

Flower Planting With No Adjacent

1 approach, code in every language

Problem description

You have n gardens labeled from 1 to n, and a list of bidirectional paths where each path [x, y] connects garden x and garden y. Every garden is directly connected to at most three other gardens.

There are four kinds of flowers, labeled 1, 2, 3, and 4. You must plant exactly one kind of flower in each garden so that any two gardens joined by a path use different kinds of flowers.

Return any valid assignment as an array of length n, where the i-th value is the flower type planted in garden i + 1. The problem guarantees that at least one valid answer exists.

Example 1

Input: n = 3, paths = [[1,2],[2,3],[3,1]]

Output: [1,2,3]

The three gardens form a triangle, so each must differ from the other two. Assigning 1, 2, and 3 satisfies every path; any permutation of three distinct types also works.

Example 2

Input: n = 4, paths = [[1,2],[3,4]]

Output: [1,2,1,2]

Gardens 1 and 2 must differ and gardens 3 and 4 must differ, but the two pairs are independent, so the pattern 1, 2, 1, 2 is valid.

Constraints

  • 1 <= n <= 10^4
  • 0 <= paths.length <= 2 * 10^4
  • paths[i].length == 2
  • 1 <= x, y <= n
  • x != y
  • Every garden has at most 3 paths connected to it

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free