Shivam Sethi

Binary matrix finding the longest possible length of all 1s
 avatar
unknown
java
3 years ago
1.2 kB
1
Indexable
public class Solution {
    public static void main(String[] args){
        int[][] arr = {{1,1,0,0,0},{1,1,1,0,0},{1,1,1,0,0},{1,1,1,0,0},{1,0,0,0,0}};
        System.out.println("Size of largest one array is "+(binaryTraverse(arr)+1));
    }


    public static int binaryTraverse(int[][] arr){
        int beg = 0;
        int end = arr.length-1;
        int mid=-1;
        boolean foundInLastCheck = false, everFoundAOne = false;
        while(beg<=end){
            if(beg==end){
                mid = beg;
            }else{
                mid = (beg+end)/2;
            }
            int found = traverseColumn(mid, arr);
            if(found>=0){
                everFoundAOne = true;
                foundInLastCheck = true;
                beg = mid+1;
            }else{
                foundInLastCheck = false;
                end = mid-1;
            }
        }
        if(everFoundAOne){
            if(foundInLastCheck)
                return mid;
            return mid-1;
        }
        return -1;
    }

    public static int traverseColumn(int col, int[][] arr){
        for(int i=0;i<arr.length;++i){
            if(arr[i][col]==1)
                return i;
        }
        return -1;
    }
}