Smallest Rectangle Enclosing Black Pixels

Note: 约等于O(nlogn)

public class Solution {
    /**
     * @param image a binary matrix with '0' and '1'
     * @param x, y the location of one of the black pixels
     * @return an integer
     */
    public int minArea(char[][] image, int x, int y) {
        // Write your code here
        if(image == null || image.length == 0) {
            return 0;
        }
        if (image[0] == null || image[0].length == 0) {
            return 0;
        }
        
        int nRow = image.length;
        int nCol = image[0].length;
        
        //find the right boarder 
        int start = y;
        int end = nCol - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (checkCol(image, mid)) {  
                start = mid;
            } else {
                end = mid;
            }
        }
        int right = start;
        if (checkCol(image, end)) {
            right = end;
        }
        
        //find the left boarder
        start = 0;
        end = y;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (checkCol(image, mid)) {
                end = mid;
            } else {
                start = mid;
            }
        }
        int left = end;
        if (checkCol(image, start)) {
            left = start;
        }
        
        //find the up boarder
        start = 0;
        end = x;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (checkRow(image, mid)) {
                end = mid;
            } else {
                start = mid;
            }
        }
        int up = end;
        if (checkRow(image, start)) {
            up = start;    
        }
        
        //find the down boarder
        start = x;
        end = nRow - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (checkRow(image, mid)) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        int down = start;
        if (checkRow(image, end)) {
            down = end;
        }
        
        
        return (right - left + 1) * (down - up + 1);
    }
    
    private boolean checkCol(char[][] image, int col) {
        for (int i = 0; i < image.length; i++) {
            if (image[i][col] == '1') {
                return true;
            }
        }
        return false;
    }
    
    private boolean checkRow(char[][] image, int row) {
        for (int i = 0; i < image[row].length; i++) {
            if (image[row][i] == '1') {
                return true;
            }
        }
        return false;
    }
} 

 

posted on 2017-05-28 05:47  codingEskimo  阅读(117)  评论(0编辑  收藏  举报

导航