Day 21 - Intuitive Java solution Leftmost Column with at Least a One

Move from top right corner to left down corner with checking if left limit (index 0) is not found.
Elements visited on each itteration for N=5 M=5:
i = 4
J From 4 to 2:
image
I = 3
J FROM 2 to 0
image
i = 2
j = 0
image
I = 1;
J = 0;
image
i = 0;
J = 0;
image

public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) {
        int min = Integer.MAX_VALUE;
        List<Integer> dimensions = binaryMatrix.dimensions();
        int rows = dimensions.get(0);
        int columns = dimensions.get(1);
        for(int i = rows - 1; i >= 0; --i){
            boolean foundOne = false;
            for(int j = columns - 1; j >= 0; --j){
                int current = binaryMatrix.get(i , j);
                if(current == 0 && j != columns - 1 && foundOne){
                    if(j <= min) {
                        min = j + 1;
                        if(min == 0)
                            return 0;
                        columns = min;
                        break;
                    }
                }else if(current == 0)
                    break;
                else if(current == 1 && j == 0)
                    return 0;
                else if(current == 1)
                    foundOne = true;
            }

        }
        return min == Integer.MAX_VALUE ? -1 : min;
    }
Comments (0)