the error ArrayIndexOutOfBoundsException in a loop
public class MaxOneBorderSize {
public static void setBorderMap(int[][] m, int[][] right, int[][] down) {
if(m == null){
return;
}
right = new int[m.length][m[0].length];
down = new int[m.length][m[0].length];
for(int row = 0; row <m.length;row++ ){
for(int col = 0; col <m[0].length; col++){
int index = 0;
int tempCol = col;
// 0 - N-1
while(tempCol<m[0].length && m[row][tempCol] == 1){
tempCol++;
index++;
}
right[row][tempCol-1] = index;
}
}
// 然后生成down的数据
for(int row = 0; row <m.length;row++ ){
for(int col = 0; col <m[0].length; col++){
int index = 0;
while(row<m.length&&m[row][col] == 1){
row++;
index++;
}
down[row-1][col] = index;
}
}
}
public static int getMaxSize(int[][] m) {
int[][] right = new int[m.length][m[0].length];
int[][] down = new int[m.length][m[0].length];
setBorderMap(m, right, down); // O(N^2); +
for (int size = Math.min(m.length, m[0].length); size != 0; size--) {
if (hasSizeOfBorder(size, right, down)) {
return size;
}
}
return 0;
}
public static boolean hasSizeOfBorder(int size, int[][] right, int[][] down) {
for (int i = 0; i != right.length - size + 1; i++) {
for (int j = 0; j != right[0].length - size + 1; j++) {
if (right[i][j] >= size && down[i][j] >= size
&& right[i + size - 1][j] >= size
&& down[i][j + size - 1] >= size) {
return true;
}
}
}
return false;
}
public static int[][] generateRandom01Matrix(int rowSize, int colSize) {
int[][] res = new int[rowSize][colSize];
for (int i = 0; i != rowSize; i++) {
for (int j = 0; j != colSize; j++) {
res[i][j] = (int) (Math.random() * 2);
}
}
return res;
}
public static void printMatrix(int[][] matrix) {
for (int i = 0; i != matrix.length; i++) {
for (int j = 0; j != matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = generateRandom01Matrix(7, 8);
printMatrix(matrix);
System.out.println(getMaxSize(matrix));
}
}
1 0 0 0 1 0 1 1
1 0 0 1 0 1 1 0
0 0 1 1 0 1 1 0
0 0 0 1 0 0 1 1
1 1 1 0 1 0 0 1
0 0 1 1 1 0 1 0
0 1 0 0 1 1 0 0
I have completed the code to get the longest side of the rectangle consists of ‘1’. But the error java.lang.ArrayIndexOutOfBoundsException has occured in
for(int row = 0; row <m.length;row++ ){
for(int col = 0; col <m[0].length; col++){
int index = 0;
int tempCol = col;
// 0 - N-1
while(tempCol<m[0].length && m[row][tempCol] == 1){
tempCol++;
index++;
}
right[row][tempCol-1] = index;
}
}
I don't have any idea about that.