// 0764. Largest Plus Sign
class Solution {
public int orderOfLargestPlusSign(int n, int[][] mines) {
int[][] grid = new int[n][n];
int[][] maxArm = new int[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
grid[i][j] = 1;
}
}
for (int[] mine : mines) {
grid[mine[0]][mine[1]] = 0;
}
for (int i = 0; i < n; ++i) {
int continuesOnes = 0;
for (int j = 0; j < n; ++j) {
continuesOnes = (continuesOnes + grid[i][j]) * grid[i][j];
maxArm[i][j] = continuesOnes;
}
continuesOnes = 0;
for (int j = n - 1; j >= 0; --j) {
continuesOnes = (continuesOnes + grid[i][j]) * grid[i][j];
maxArm[i][j] = Math.min(maxArm[i][j], continuesOnes);
}
}
for (int j = 0; j < n; ++j) {
int continuesOnes = 0;
for (int i = 0; i < n; ++i) {
continuesOnes = (continuesOnes + grid[i][j]) * grid[i][j];
maxArm[i][j] = Math.min(maxArm[i][j], continuesOnes);
}
continuesOnes = 0;
for (int i = n - 1; i >= 0; --i) {
continuesOnes = (continuesOnes + grid[i][j]) * grid[i][j];
maxArm[i][j] = Math.min(maxArm[i][j], continuesOnes);
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ans = Math.max(ans, maxArm[i][j]);
}
}
return ans;
}
}
学习笔记:
这是一道说是动态规划但似乎又不是动态规划的题目。
因为动态规划应该是无后效性的,但他分四个方向推了四次。
这里代码用逻辑来写应该是
if (grid[i][j] == 1) {
++continuesOnes;
} else {
continuesOnes = 0;
}
但是想不用愚蠢的if语句,可以先加1或0,然后再乘1或0。
continuesOnes = (continuesOnes + grid[i][j]) * grid[i][j];
用if语句24ms,直接计算25ms,反而是用了if语句更快,只能说现在的CPU可能在分支预判上做得不错了,导致不用if语句的优势反而失去了。
但不用if语句的妙处还是很有滋味的。