常规做法dfs bfs O(mn)
bfs需要新建一个class存坐标 dfs不用存 更简便一点 记得每次访问过1后要给他设置成0
public class Solution {
int minX = Integer.MAX_VALUE, maxX = 0, minY = Integer.MAX_VALUE, maxY = 0;
public int minArea(char[][] image, int x, int y) {
if ( image == null || image.length == 0 || image[ 0 ].length == 0 )
return 0;
dfs ( image, x, y );
return ( maxX - minX + 1 ) * ( maxY - minY + 1 );
}
public void dfs ( char[][] image, int x, int y ){
int m = image.length;
int n = image[ 0 ].length;
if ( x < 0 || x >= m || y < 0 || y >= n || image [x][y] == '0' )
return;
image[x][y] = '0';
minX = Math.min( minX, x );
maxX = Math.max( maxX, x );
minY = Math.min( minY, y );
maxY = Math.max( maxY, y );
dfs ( image, x - 1, y );
dfs ( image, x + 1, y );
dfs ( image, x, y - 1 );
dfs ( image, x, y + 1 );
}
}
还有更快的就是binary search 做四次 寻找边界
[0,y) 找left 找的是最左边的1
[y + 1, n) 找right 找的是右边第一个0
top bottom同理
那个boolean只是为了区分这次是往哪边找 不同方向start和end移动方式不一样
最后算面积的时候right - left不用再加1了
public class Solution {
public int minArea(char[][] image, int x, int y) {
int m = image.length;
int n = image[ 0 ].length;
int left = searchCol ( image, 0, y, true );
int right = searchCol ( image, y + 1, n, false );
int top = searchRow ( image, 0, x, true );
int bottom = searchRow ( image, x + 1, m, false );
return ( right - left ) * ( bottom - top );
}
public int searchCol ( char[][]image, int start, int end, boolean left ){
int row = image.length;
while ( start < end ){
int mid = start + ( end - start ) / 2;
int k = 0;
while ( k < row && image[ k ][ mid ] == '0')
k ++;
if ( k < row == left )
end = mid;
else
start = mid + 1;
}
return start;
}
public int searchRow ( char[][] image, int start, int end, boolean top ){
int col = image[ 0 ].length;
while ( start < end ){
int mid = start + ( end - start )/ 2;
int k = 0;
while ( k < col && image [ mid ][ k ] == '0' )
k ++;
if ( k < col == top )
end = mid;
else
start = mid + 1;
}
return start;
}
}