★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10693911.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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
.
图像由一个二进制矩阵表示,其中0为白色像素,1为黑色像素。黑色像素连接,即只有一个黑色区域。像素水平和垂直连接。给定一个黑色像素的位置(x, y),返回包围所有黑色像素的最小(轴对齐)矩形的区域。
例如,给出以下图像:
[ "0010", "0110", "0100" ]
X=0,Y=2,
返回6。
Solution:
1 class Solution { 2 func minArea(_ image:inout [String],_ x:Int,_ y:Int) -> Int { 3 var m:Int = image.count 4 var n:Int = image[0].count 5 var up:Int = binary_search(&image, true, 0, x, 0, n, true) 6 var down:Int = binary_search(&image, true, x + 1, m, 0, n, false) 7 var left:Int = binary_search(&image, false, 0, y, up, down, true) 8 var right:Int = binary_search(&image, false, y + 1, n, up, down, false) 9 return (right - left) * (down - up) 10 } 11 12 // Binary Search 13 func binary_search(_ image:inout [String],_ h:Bool,_ i:Int,_ j:Int,_ low:Int,_ high:Int,_ opt:Bool) -> Int 14 { 15 var i = i 16 var j = j 17 while (i < j) 18 { 19 var k:Int = low 20 var mid:Int = (i + j) / 2 21 while (k < high && (h ? image[mid][k] : image[k][mid]) == "0") 22 { 23 k += 1 24 } 25 if (k < high) == opt{ j = mid } 26 else{ i = mid + 1 } 27 } 28 return i 29 } 30 } 31 32 //String扩展 33 extension String { 34 //subscript函数可以检索数组中的值 35 //直接按照索引方式截取指定索引的字符 36 subscript (_ i: Int) -> Character { 37 //读取字符 38 get {return self[index(startIndex, offsetBy: i)]} 39 } 40 }
点击:Playground测试
1 var sol = Solution() 2 var arr:[String] = ["0010","0110","0100"] 3 var x:Int = 0 4 var y:Int = 2 5 print(sol.minArea(&arr,x,y)) 6 //Print 6