最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

※Leetcode Day16 2

2022-04-21 22:18 作者:我喜歡喝一點(diǎn)點(diǎn)  | 我要投稿

200. 島嶼數(shù)量

你一個由 '1'(陸地)和 '0'(水)組成的的二維網(wǎng)格,請你計(jì)算網(wǎng)格中島嶼的數(shù)量。


島嶼總是被水包圍,并且每座島嶼只能由水平方向和/或豎直方向上相鄰的陸地連接形成。


此外,你可以假設(shè)該網(wǎng)格的四條邊均被水包圍。


?


示例 1:


輸入:grid = [

? ["1","1","1","1","0"],

? ["1","1","0","1","0"],

? ["1","1","0","0","0"],

? ["0","0","0","0","0"]

]

輸出:1

示例 2:


輸入:grid = [

? ["1","1","0","0","0"],

? ["1","1","0","0","0"],

? ["0","0","1","0","0"],

? ["0","0","0","1","1"]

]

輸出:3


這道題蠻重要的,頻率蠻高,做個標(biāo)記吧,dfs就行,遍歷過的話就將這個設(shè)置為0

class?Solution:

????def?numIslands(self,?grid:?List[List[str]])?->?int:

????????clen=len(grid)

????????llen=len(grid[0])

????????def?dfs(grid,i,j):

????????????if?not?0<=i<clen?or?not?0<=j<llen?or?grid[i][j]=='0':

????????????????return

????????????grid[i][j]='0'

????????????dfs(grid,i+1,j)

????????????dfs(grid,i-1,j)

????????????dfs(grid,i,j+1)

????????????dfs(grid,i,j-1)

????????res=0

????????for?i?in?range(clen):

????????????for?j?in?range(llen):

????????????????if?grid[i][j]=='1':

????????????????????dfs(grid,i,j)

????????????????????res+=1

????????return?res


后面進(jìn)行了一個剪枝,就是先判斷能不能去,不為1的就不去。


優(yōu)化后大概是優(yōu)化了1/3這樣,還不錯的

※Leetcode Day16 2的評論 (共 條)

分享到微博請遵守國家法律
嘉善县| 鹰潭市| 长武县| 清苑县| 建宁县| 米泉市| 灵石县| 济源市| 库车县| 石楼县| 白玉县| 赤城县| 兴山县| 鄂托克前旗| 鄂托克旗| 茌平县| 延寿县| 谢通门县| 云南省| 菏泽市| 大同市| 海淀区| 六盘水市| 法库县| 黄梅县| 洛川县| 铁力市| 平凉市| 天峻县| 孝昌县| 文山县| 施秉县| 宁安市| 松溪县| 东光县| 贵定县| 赤壁市| 宁阳县| 临漳县| 若尔盖县| 攀枝花市|