Find the largest square with all 1s in a 2D 01 matrix
Sample
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
return 4
The dynamic programming method, we can first find the maximum side length of the square, the formula we deduce is, the original array is arr[][];
f[][] is the table to store the result, when the largest square includes arr[] When i][j], f[i][j] = min(f[i-1][j-1],f[i][j-1],f[i-1][j]) +1; When f[i][j] is not included, f[i][j] = 0; the maximum side length at this time is num = max(f[i][j],num )
f[][] is the table to store the result, when the largest square includes arr[] When i][j], f[i][j] = min(f[i-1][j-1],f[i][j-1],f[i-1][j]) +1; When f[i][j] is not included, f[i][j] = 0; the maximum side length at this time is num = max(f[i][j],num )
The complete code is as follows:
package lintcode; import java.util.Scanner; /** * Created by Taoyongpan on 2017/11/15. * 436, find the largest square with all 1s in a two-dimensional 01 matrix * The idea of dynamic programming * Find the longest side of the square */ public class MaxSquare { public static int SquareMax(int[][] arr){ int n = arr.length; int m = arr[0].length; int num = 0; int[][] f = new int[n+1][m+1]; if (n<=0||m<=0){ return num; } //initialize the f array for (int i = 0;i<n;i++){ f[i][0] = arr[i][0]; num = Math.max(f[i][0],num); } for (int j = 0; j<m;j++){ f[0][j] = arr[0][j]; num = Math.max(f[0][j],num); } for (int i = 1;i<n;i++){ for (int j = 1;j<m;j++){ if (arr[i][j]==1) f[i][j] = Math.min(Math.min(f[i-1][j-1],f[i][j-1]),f[i-1][j])+1; else f[i][j] = 0; num = Math.max(f[i][j],num); } } return num; } // main function public static void main(String[] args){ Scanner sc = new Scanner(System.in); while (sc.hasNext()){ int n = sc.nextInt(); int m = sc.nextInt(); int[][] arr = new int[n+1][m+1]; for (int i = 0 ;i<n;i++){ for (int j = 0;j<m;j++){ arr[i][j] = sc.nextInt(); } } System.out.println(SquareMax(arr)); } } }