★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-vkopjpkv-kt.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.git
For example, given the following image:github
[ "0010", "0110", "0100" ]
and x = 0
, y = 2
,數組
Return 6
.微信
圖像由一個二進制矩陣表示,其中0爲白色像素,1爲黑色像素。黑色像素鏈接,即只有一個黑色區域。像素水平和垂直鏈接。給定一個黑色像素的位置(x, y),返回包圍全部黑色像素的最小(軸對齊)矩形的區域。函數
例如,給出如下圖像:測試
[ "0010", "0110", "0100" ]
X=0,Y=2,spa
返回6。code
Solution:htm
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