给你一个奇怪的打印机,它有如下两个特殊的打印规则:
每一次操作时,打印机会用同一种颜色打印一个矩形的形状,每次打印会覆盖矩形对应格子里原本的颜色。
一旦矩形根据上面的规则使用了一种颜色,那么 相同的颜色不能再被使用 。
给你一个初始没有颜色的 m x n 的矩形 targetGrid ,其中 targetGrid[row][col] 是位置 (row, col) 的颜色。
如果你能按照上述规则打印出矩形 targetGrid ,请你返回 true ,否则返回 false 。
示例 1:
输入:targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]
输出:true
示例 2:
输入:targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]
输出:true
示例 3:
输入:targetGrid = [[1,2,1],[2,1,2],[1,2,1]]
输出:false
解释:没有办法得到 targetGrid ,因为每一轮操作使用的颜色互不相同。
示例 4:
输入:targetGrid = [[1,1,1],[3,1,3]]
输出:false
提示:
m == targetGrid.length
n == targetGrid[i].length
1 <= m, n <= 60
1 <= targetGrid[row][col] <= 60
思路:拓扑排序。对于每种颜色,我们标记有多少个其他颜色的块覆盖在它上边,这个颜色的入度就加1,之后按照拓扑排序进行合法性判断即可。
class Solution {
public boolean isPrintable(int[][] targetGrid) {
int n = targetGrid.length;
int m = targetGrid[0].length;
int size = 60;
int[] minx = new int[size + 1];
int[] miny = new int[size + 1];
int[] maxx = new int[size + 1];
int[] maxy = new int[size + 1];
int[] ingree = new int[size + 1];
boolean[] used = new boolean[size + 1];
Arrays.fill(minx, 100);
Arrays.fill(miny, 100);
Arrays.fill(maxx, -1);
Arrays.fill(maxy, -1);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
minx[targetGrid[i][j]] = Math.min(minx[targetGrid[i][j]], i);
miny[targetGrid[i][j]] = Math.min(miny[targetGrid[i][j]], j);
maxx[targetGrid[i][j]] = Math.max(maxx[targetGrid[i][j]], i);
maxy[targetGrid[i][j]] = Math.max(maxy[targetGrid[i][j]], j);
}
for (int i = 1; i <= 60; i++) {
if (maxx[i] == -1 || used[i])
continue;
used[i] = true;
for (int x = minx[i]; x <= maxx[i]; x++)
for (int y = miny[i]; y <= maxy[i]; y++)
if (targetGrid[x][y] != i)
ingree[i]++;
}
used = new boolean[size + 1];
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i <= 60; i++) {
if (maxx[i] == -1)
continue;
if (ingree[i] == 0) {
q.add(i);
used[i] = true;
}
}
while (!q.isEmpty()) {
int now = q.poll();
for (int i = minx[now]; i <= maxx[now]; i++)
for (int j = miny[now]; j <= maxy[now]; j++)
for (int k = 1; k <= 60; k++) {
if (maxx[k] == -1 || k == now || targetGrid[i][j] != now)
continue;
if (minx[k] <= i && maxx[k] >= i && miny[k] <= j && maxy[k] >= j)
ingree[k]--;
}
for (int i = 0; i <= 60; i++) {
if (used[i] || maxx[i] == -1 || ingree[i] != 0)
continue;
used[i] = true;
q.add(i);
}
}
for (int i = 1; i <= 60; i++) {
if (maxx[i] == -1)
continue;
if (!used[i])
return false;
}
return true;
}
}