题解 | #小美的平衡矩阵#
思路
使用前缀和
- 使用前缀和(Prefix Sum)来快速计算任意子矩阵中 0 和 1 的数量。
代码如下:
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] matrix = new int[n + 1][n + 1];
in.nextLine();
// 注意 hasNext 和 hasNextLine 的区别
int i = 1;
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
//System.out.println(str.length());
for (int chIndex = 0; chIndex < str.length(); chIndex++) {
matrix[i][chIndex + 1] = str.charAt(chIndex) - '0';
}
i++;
}
//Arrays.stream(matrix).forEach(item -> System.out.println(Arrays.toString(item)));
int[][] dp = new int[n + 1][n + 1];
int[] ret = new int[n + 1];
for (int rowIndex = 1; rowIndex <= n ; rowIndex++) {
for (int colIndex = 1; colIndex <= n; colIndex++) {
dp[rowIndex][colIndex] = dp[rowIndex - 1][colIndex] + dp[rowIndex][colIndex - 1]
-
dp[rowIndex - 1][colIndex - 1] + matrix[rowIndex][colIndex];
}
}
for (int j = 2; j <= n; j = j + 2) {
for (int rowIndex = 1; rowIndex + j - 1 <= n; rowIndex++) {
for (int colIndex = 1; colIndex + j - 1 <= n; colIndex++) {
int sum = dp[rowIndex + j - 1][colIndex + j - 1] - dp[rowIndex + j - 1][colIndex
- 1]
- dp[rowIndex - 1][colIndex + j - 1] + dp[rowIndex - 1][colIndex - 1];
if (sum == j * j / 2) {
ret[j]++;
}
}
}
}
for (int j = 1; j < n + 1; j++) {
System.out.println(ret[j]);
}
}
}
参考文章链接:
【基础算法总结】前缀和
https://blog.csdn.net/2301_77900444/article/details/141491479?spm=1001.2014.3001.5506
小美的平衡矩阵(前缀和例题 -- 美团笔试编程题)
https://blog.csdn.net/weixin_44343938/article/details/137128412

