Skip to content

Smallest Rectangle Enclosing Black Pixels (diff)

Tim_Gao edited this page Sep 18, 2016 · 1 revision
  1. This very nice. Different from traditional DFS, you don't have to find every possible route. You just need to cover every black pixel.
public class Solution {
    private void dfs(char[][] image, int x, int y, ArrayList<Integer> coordinate){
        if(x<0 || x>=image.length || y<0 || y>= image[0].length || image[x][y] !='1' ){
            return;
        }
        coordinate.set(0, Math.min(coordinate.get(0), x));
        coordinate.set(1, Math.min(coordinate.get(1), y));
        coordinate.set(2, Math.max(coordinate.get(2), x));
        coordinate.set(3, Math.max(coordinate.get(3), y));
        image[x][y] = '2';
        dfs(image, x-1, y, coordinate);
        dfs(image, x+1, y, coordinate);
        dfs(image, x, y-1, coordinate);
        dfs(image, x, y+1, coordinate);
    }
    public int minArea(char[][] image, int x, int y) {
        ArrayList<Integer> coordinate = new ArrayList<>();
        //0 -> x1, as small as possible,  1 -> y1 as small as possible
        //2 -> x2, as large as possible,  3 -> y2 as large as possible
        coordinate.add(Integer.MAX_VALUE);
        coordinate.add(Integer.MAX_VALUE);
        coordinate.add(Integer.MIN_VALUE);
        coordinate.add(Integer.MIN_VALUE);
        dfs(image, x, y, coordinate);
        return (coordinate.get(2)-coordinate.get(0)+1) * (coordinate.get(3) - coordinate.get(1)+1);
    }
}

Clone this wiki locally