Leetcode - Smallest Rectangle Enclosing Black Pixels

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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/fd6a4774e3fe
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞