Here my approach is dp[i][j] gives you the minimum cost needed to paint a rectangle ending at i,j.
if it’s the cell at i,j is a black cell
op1 = Math.max(i+1,j+1)
op2 = dp[i-1][j] + dp[i][j-1] +1
dp[i][j] = Math.min(op1,op2)
What's wrong with my approach
Here my approach is dp[i][j] gives you the minimum cost needed to paint a rectangle ending at i,j. if it’s the cell at i,j is a black cell op1 = Math.max(i+1,j+1) op2 = dp[i-1][j] + dp[i][j-1]-dp[i-1][j-1] +1 dp[i][j] = Math.min(op1,op2)
import java.util.*;
public class Main {
public static void main (String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] dp = new int[n][n];
int[][] arr = new int[n][n];
sc.nextLine();
for(int i = 0;i<n;i++)
{
String s = sc.nextLine();
String [] temp = s.split("");
for(int j =0;j<temp.length;j++)
{
if(temp[j].equals("#"))
arr[i][j] = 0;
else
arr[i][j] = 1;
}
}
System.out.println(painting_cost(arr,dp));
}
private static int painting_cost(int[][] arr , int[][] dp)
{
int n = arr.length;
if(arr[0][0]==0)
dp[0][0] = 1;
else
dp[0][0] = 0;
//filling the first row
for(int i=1;i<n;i++)
{
if(arr[0][i] == 0)
dp[0][i] = dp[0][i-1]+1;
else
dp[0][i] = dp[0][i-1];
}
//filling the first col
for(int j =1;j<n;j++)
{
if(arr[j][0] ==0)
dp[j][0] = 1+dp[j-1][0];
else
dp[j][0] = dp[j-1][0];
}
//filling the remaining matrix
for(int i =1;i<n;i++)
for(int j =1;j<n;j++)
{
if(arr[i][j] == 0)
{
int op1 = Math.max(i+1,j+1);
int op2 = dp[i-1][j] + dp[i][j-1] -dp[i-1][j-1] +1;
dp[i][j]= Math.min(op1,op2);
}
else
{
int op1 = Math.max(i+1,j+1);
int op2 = dp[i-1][j] + dp[i][j-1] -dp[i-1][j-1];
dp[i][j] = Math.min(op1,op2);
}
}
return dp[n-1][n-1];
}
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
Solve the problem for rectangle W×H (W≥H).
Of course, we can cover all rectangle with itself for cost W.
To get something smaller than W we have to leave at least one column uncovered — otherwise we pay at least sum of w over all rectangles which is at least W.
This gives us an idea to use DP on rectangles to solve the problem: dp[x1][x2][y1][y2] is minimal cost to cover the rectangle [x1;x2)×[y1;y2).
It is initialized by max(x2−x1,y2−y1), and we have to try not to cover every column/row.
Of course, we have to check if it is all white from the beginning; to do that we will precalculate 2D prefix sums. Total complexity is O(n5).
N is upto 50 .
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.