常规做法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;
}
}

本文提供两种高效算法实现:深度优先搜索(DFS)和二分查找(Binary Search),用于确定二维矩阵中1元素包围的最小矩形区域面积。通过递归深度优先遍历定位边界,并采用二分查找快速确定上下左右边界。
1万+

被折叠的 条评论
为什么被折叠?



