713979. Walls Coloring II

Hard

Walls Coloring II

Slug: walls-coloring-ii--170647 Difficulty: Hard Id: 713979 Topic Tags: Dynamic Programming

Summary

The Walls Coloring II problem is a classic dynamic programming problem that involves coloring walls with different colors to minimize the maximum number of adjacent walls. The goal is to find an optimal color scheme for a given set of wall configurations.

Given a grid of dimensions m x n, where each cell represents a wall and its corresponding value indicates whether it can be colored (1) or not (0), we need to determine the minimum cost to color all the walls such that no two adjacent walls have the same color. The cost is calculated based on the number of different colors used.

Detailed Explanation

The problem can be solved using dynamic programming. We create a 2D array dp[][] where dp[i][j] represents the minimum cost to color the first i rows and j columns. The base case is when we have reached the last row, in which case the minimum cost is 0 (since there are no more walls to color).

The recurrence relation is as follows:

  • If the current wall can be colored (i.e., its value is 1), then we consider two options:
    • Color the current wall with a new color: dp[i][j] = min(dp[i-1][j-1]) + 1 (since one more color is used)
    • Continue using the same color as the previous wall: dp[i][j] = min(dp[i-1][j-1])
  • If the current wall cannot be colored (i.e., its value is 0), then we can only continue using the same color as the previous wall: dp[i][j] = min(dp[i-1][j-1])

The final answer is stored in dp[m][n], which represents the minimum cost to color all the walls.

Here's an ASCII art diagram illustrating the problem:

 0 0 1
 1 1 0
 1 0 1

In this example, we have a 3x3 grid where each cell represents a wall. The values 0 and 1 indicate whether a wall can be colored or not.

Time complexity: O(mn) Space complexity: O(mn)

Optimized Solutions

Java

View on GeeksforGeeks
public int wallsColoring(int[][] dp) {
    int m = dp.length;
    int n = dp[0].length;
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            if (dp[i][j] == 1) {
                dp[i][j] = Math.min(dp[i-1][j-1], dp[i-1][j]) + 1;
            } else {
                dp[i][j] = dp[i-1][j];
            }
        }
    }
    return dp[m-1][n-1];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.