[Swift]LeetCode302. 包含黑色像素的最小矩形 $ Smallest Rectangle Enclosing Black Pixels
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了