我们可以利用数组
d
p
[
i
]
[
j
]
dp[i][j]
dp[i][j]来记录原数组中
[
i
]
[
j
]
[i][j]
[i][j]位上的元素在四个方向上连续出现1的次数。我们在这里使用
k
=
0
,
1
,
2
,
3
k=0,1,2,3
k=0,1,2,3来表示左、上、右、下四个方向。以向左为例,我们的状态转移公式为:
d
p
[
i
]
[
j
]
[
0
]
=
{
0
,
g
r
i
d
[
i
]
[
j
]
=
0
d
p
[
i
]
[
j
−
1
]
[
0
]
+
1
,
g
r
i
d
[
i
]
[
j
]
=
1
dp[i][j][0]=\left\{0,grid[i][j]=0dp[i][j−1][0]+1,grid[i][j]=1\right.
dp[i][j][0]={0,grid[i][j]=0dp[i][j−1][0]+1,grid[i][j]=1
而后我们遍历每一个位置,在他的四个方向上选择最小值作为当前的最大边长。
class Solution {
public:
int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {
vector<vector<int>> dp(n, vector<int>(n, n));
unordered_set<int> banned;
for (auto &&vec : mines) {
banned.emplace(vec[0] * n + vec[1]);
}
int ans = 0;
for (int i = 0; i < n; i++) {
int count = 0;
/* left */
for (int j = 0; j < n; j++) {
if (banned.count(i * n + j)) {
count = 0;
} else {
count++;
}
dp[i][j] = min(dp[i][j], count);
}
count = 0;
/* right */
for (int j = n - 1; j >= 0; j--) {
if (banned.count(i * n + j)) {
count = 0;
} else {
count++;
}
dp[i][j] = min(dp[i][j], count);
}
}
for (int i = 0; i < n; i++) {
int count = 0;
/* up */
for (int j = 0; j < n; j++) {
if (banned.count(j * n + i)) {
count = 0;
} else {
count++;
}
dp[j][i] = min(dp[j][i], count);
}
count = 0;
/* down */
for (int j = n - 1; j >= 0; j--) {
if (banned.count(j * n + i)) {
count = 0;
} else {
count++;
}
dp[j][i] = min(dp[j][i], count);
ans = max(ans, dp[j][i]);
}
}
return ans;
}
};