(Largest block)
Given a square matrix with the elements 0 or 1, write a program to find a maximum square submatrix whose elements are all 1s. Your program should prompt the user to enter the number of rows in the matrix. The program then displays the location of the first element in the maximum square submatrix and the number of the rows in the submatrix.
Here is a sample run:
Enter the number of rows in the matrix:
5
Enter the matrix row by row:
1 0 1 0 1 1 1 1 0 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1
The maximum square submatrix is at
(2, 2)
with size3
My solution is this:
(I didn't make it prompt an input because my computer hasn't arrived and the ide on my phone can't use text files as input. I didn't want to type in all the numbers to try different inputs.)
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 0, 1, 0, 1},
{1, 1, 1, 0, 1},
{1, 0, 1, 1, 1},
{1, 0, 1, 1, 1},
{1, 0, 1, 1, 1}
};
//Check each location for sub-squares
int[] largestBlock = new int[3];
int maxSize = 0;
for (int i = 0; i < matrix.length - 1; i++) {
for (int j = 0; j < matrix[i].length - 1; j++) {
int squareSize = 0;
while (isSquare(i, j, squareSize, matrix)) {
squareSize++;
}
if (squareSize > maxSize) {
largestBlock[0] = i;
largestBlock[1] = j;
maxSize = squareSize;
}
}
}
largestBlock[2] = maxSize + 1;
System.out.println("The first largest sub-square is located at (" + largestBlock[0]
+ ", " + largestBlock[1] + ") and is of size " + largestBlock[2]);
}
public static boolean isSquare(int row, int column, int squareSize, int[][] matrix) {
int size = squareSize + 2;
if (row + size - 1 >= matrix.length || column + size - 1 >= matrix.length)
return false;
for (int i = row; i < row + size; i++) {
for (int j = column; j < column + size; j++) {
if (matrix[i][j] != 1)
return false;
}
}
return true;
}
}