An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically. Given the location (x, y) of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.
For example, given the following image:
[ "0010", "0110", "0100" ]
and x = 0, y = 2,
Return 6.
Solution
publicclassSolution {publicintminArea(char[][] image,int x,int y) {if (image ==null||image.length==0) return0;int row =image.length;int column = image[0].length;if (!validate(x, y, row, column)) return0;List<Point> pointList =newArrayList<>();boolean[][] visit =newboolean[row][column];traverse(image, visit, x, y, row, column, pointList);if (pointList.isEmpty()) return0;Point point =pointList.get(0);int minX =point.x;int maxX =point.x;int minY =point.y;int maxY =point.y;for (int i =1; i <pointList.size(); i++) { point =pointList.get(i); minX =Math.min(minX,point.x); maxX =Math.max(maxX,point.x); minY =Math.min(minY,point.y); maxY =Math.max(maxY,point.y); }return (Math.abs(minX - maxX) +1) * (Math.abs(minY - maxY) +1); }privatevoidtraverse(char[][] image,boolean[][] visit,int x,int y,int row,int column,List<Point> points) {if (!validate(x, y, row, column)|| visit[x][y]) return; visit[x][y] =true;if (image[x][y] =='1') {points.add(newPoint(x, y));traverse(image, visit, x +1, y, row, column, points);traverse(image, visit, x -1, y, row, column, points);traverse(image, visit, x, y +1, row, column, points);traverse(image, visit, x, y -1, row, column, points); } }privateclassPoint {int x;int y;publicPoint(int x,int y) {this.x= x;this.y= y; } }privatebooleanvalidate(int x,int y,int row,int column) {return x >=0&& x < row && y >=0&& y < column; }}