Skip to the code
+25 XP

#310 Color the Dashboard Regions

medium

A heat-map dashboard has n regions numbered 0 to n - 1. borders lists pairs [a, b] of regions that touch. The designer has colors colors and wants touching regions to have different colors.

Write countColorings(n, borders, colors) that returns how many ways there are to give every region one color so that no two touching regions share a color. Colorings that differ in at least one region count as different.

Example 1

Input: n = 3, borders = [[0,1],[1,2]], colors = 2
Output: 2

In a chain of 3 regions with 2 colors, the colors must alternate, and either color can start.

Example 2

Input: n = 3, borders = [[0,1],[1,2],[0,2]], colors = 2
Output: 0

Three regions that all touch each other need 3 different colors.

Constraints

  • 1 <= n <= 20
  • 0 <= borders.length <= 190
  • 1 <= colors <= 4
  • No border connects a region to itself.
  • The answer is at most 1,000,000.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).