|
| 1 | +/** |
| 2 | + * 302. Smallest Rectangle Enclosing Black Pixels |
| 3 | + * https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an m x n binary matrix image where 0 represents a white pixel and 1 represents |
| 7 | + * a black pixel. |
| 8 | + * |
| 9 | + * The black pixels are connected (i.e., there is only one black region). Pixels are connected |
| 10 | + * horizontally and vertically. |
| 11 | + * |
| 12 | + * Given two integers x and y that represents the location of one of the black pixels, return |
| 13 | + * the area of the smallest (axis-aligned) rectangle that encloses all black pixels. |
| 14 | + * |
| 15 | + * You must write an algorithm with less than O(mn) runtime complexity |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {character[][]} image |
| 20 | + * @param {number} x |
| 21 | + * @param {number} y |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var minArea = function(image, x, y) { |
| 25 | + const rows = image.length; |
| 26 | + const cols = image[0].length; |
| 27 | + const top = binarySearch(0, x, true, true); |
| 28 | + const bottom = binarySearch(x, rows - 1, true, false); |
| 29 | + const left = binarySearch(0, y, false, true); |
| 30 | + const right = binarySearch(y, cols - 1, false, false); |
| 31 | + |
| 32 | + return (bottom - top + 1) * (right - left + 1); |
| 33 | + |
| 34 | + function binarySearch(start, end, isRow, isMin) { |
| 35 | + let result = isMin ? end : start; |
| 36 | + while (start <= end) { |
| 37 | + const mid = Math.floor((start + end) / 2); |
| 38 | + let hasBlack = false; |
| 39 | + for (let i = 0; i < (isRow ? cols : rows); i++) { |
| 40 | + const pixel = isRow ? image[mid][i] : image[i][mid]; |
| 41 | + if (pixel === '1') { |
| 42 | + hasBlack = true; |
| 43 | + break; |
| 44 | + } |
| 45 | + } |
| 46 | + if (hasBlack) { |
| 47 | + result = mid; |
| 48 | + if (isMin) { |
| 49 | + end = mid - 1; |
| 50 | + } else { |
| 51 | + start = mid + 1; |
| 52 | + } |
| 53 | + } else { |
| 54 | + if (isMin) { |
| 55 | + start = mid + 1; |
| 56 | + } else { |
| 57 | + end = mid - 1; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + return result; |
| 62 | + } |
| 63 | +}; |
0 commit comments