Leetcode - Smallest Rectangle Enclosing Black Pixels

weixin_33912445發表於2016-10-13

My code:

public class Solution {
    int row = 0;
    int col = 0;
    public int minArea(char[][] image, int x, int y) {
        if (image == null || image.length == 0 || image[0].length == 0) {
            return 0;
        }
        
        this.row = image.length;
        this.col = image[0].length;
        
        int top = searchRow(image, 0, x - 1, false);
        int bottom = searchRow(image, x + 1, row - 1, true);
        
        int left = searchCol(image, 0, y - 1, false);
        int right = searchCol(image, y + 1, col - 1, true);
        
        return (right - left + 1) * (bottom - top + 1);
    }
    
    private int searchRow(char[][] image, int begin, int end, boolean flag) {
        while (begin <= end) {
            int mid = begin + (end - begin) / 2;
            boolean isBlack = false;
            for (int j = 0; j < col; j++) {
                if (image[mid][j] == '1') {
                    isBlack = true;
                    break;
                }
            }
            if (isBlack) {
                if (flag) {
                    begin = mid + 1;
                }
                else {
                    end = mid - 1;
                }
            }
            else {
                if (flag) {
                    end = mid - 1;
                }
                else {
                    begin = mid + 1;
                }
            }
        }
        return flag ? end : begin;
    }
    
    private int searchCol(char[][] image, int begin, int end, boolean flag) {
        while (begin <= end) {
            int mid = begin + (end - begin) / 2;
            boolean isBlack = false;
            for (int j = 0; j < row; j++) {
                if (image[j][mid] == '1') {
                    isBlack = true;
                    break;
                }
            }
            if (isBlack) {
                if (flag) {
                    begin = mid + 1;
                }
                else {
                    end = mid - 1;
                }
            }
            else {
                if (flag) {
                    end = mid - 1;
                }
                else {
                    begin = mid + 1;
                }
            }
        }
        return flag ? end : begin;
    }
}

reference:
https://discuss.leetcode.com/topic/29006/c-java-python-binary-search-solution-with-explanation

看了答案知道怎麼寫,然後自己寫了出來。
比答案要複雜些,當更容易理解些。
比如,行掃描。
對於(x, y) 上面的行,我們需要找到最小的那一行,他是black
對於(x, y) 下面的行,我們需要找到最大的那一行,他是black

列掃描也差不多。

然後邏輯就清楚了。
下面的問題在於,如果最大程度得程式碼複用。

Anyway, Good luck, Richardo! -- 10/12/2016

相關文章