1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
#include <iostream>
#include <vector>
#include <queue>
struct Color {
int x1 = 60;
int x2 = -1;
int y1 = 60;
int y2 = -1;
void insert(int x, int y) {
x1 = std::min(x1, x);
x2 = std::max(x2, x);
y1 = std::min(y1, y);
y2 = std::max(y2, y);
}
bool contains(int x, int y) {
if (x < x1 || x > x2) {
return false;
}
if (y < y1 || y > y2) {
return false;
}
return true;
}
};
class Solution {
public:
bool isPrintable(std::vector<std::vector<int>>& targetGrid) {
int num = 60;
int maxn = -1;
int m = targetGrid.size();
int n = targetGrid[0].size();
std::vector<Color> colors(num);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int c = targetGrid[i][j] - 1;
maxn = std::max(c, maxn);
colors[c].insert(i, j);
}
}
++maxn;
std::vector<std::vector<int>> adj(maxn, std::vector<int>(maxn, false));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int c = targetGrid[i][j] - 1;
for (int d = 0; d < maxn; ++d) {
if (colors[d].contains(i, j)) {
adj[d][c] = true;
}
}
}
}
int cnt = 0;
std::vector<int> inDegree(maxn, 0);
for (int i = 0; i < maxn; ++i) {
for (int j = 0; j < maxn; ++j) {
if (adj[i][j] && i != j) {
++inDegree[j];
}
}
}
std::queue<int> q;
for (int i = 0; i < maxn; ++i) {
if (inDegree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int i = q.front();
q.pop();
++cnt;
for (int j = 0; j < maxn; ++j) {
if (!adj[i][j] || i == j) {
continue;
}
--inDegree[j];
if (inDegree[j] == 0) {
q.push(j);
}
}
}
return cnt == maxn;
}
};
|