摘要:解題思路標(biāo)零法對(duì)這個(gè)矩陣進(jìn)行循環(huán)訪問(wèn)每一個(gè)點(diǎn)當(dāng)這個(gè)點(diǎn)等于,島嶼數(shù)量,與其同時(shí)用算法訪問(wèn)周圍的其他點(diǎn),進(jìn)行同樣的操作且將訪問(wèn)過(guò)且等于的點(diǎn)標(biāo)記為零。版本島嶼數(shù)量搜索右邊搜索左邊搜索下邊搜索上邊
Q: Number of Islands
Given a 2d grid map of "1"s (land) and "0"s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
解題思路標(biāo)零法
對(duì)這個(gè)矩陣進(jìn)行循環(huán)訪問(wèn)每一個(gè)點(diǎn);
當(dāng)這個(gè)點(diǎn)等于 1,島嶼數(shù)量 count++,與其同時(shí)用 dfs 算法(depth first search)訪問(wèn)周圍的其他點(diǎn),進(jìn)行同樣的操作;
且將訪問(wèn)過(guò)且等于 1 的點(diǎn)標(biāo)記為零。
/** * @param {character[][]} grid * @return {number} */ var numIslands = function(grid) { var count = 0 // 島嶼數(shù)量 if (grid.length === 0) return count for (var i = 0; i < grid.length; i++) { for(var j = 0; j < grid[0].length; j++) { if (grid[i][j] === "1") { dfsSearch(grid, i, j) count++ } } } return count }; function dfsSearch(grid, i, j) { if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) return; if(grid[i][j] === "1"){ grid[i][j] = "0"; dfsSearch(grid, i + 1, j); // 搜索右邊 dfsSearch(grid, i - 1, j); // 搜索左邊 dfsSearch(grid, i, j + 1); // 搜索下邊 dfsSearch(grid, i, j - 1); // 搜索上邊 } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/98029.html
摘要:同時(shí)我們每找到一個(gè),就將其標(biāo)為,這樣就能把整個(gè)島嶼變成。我們只要記錄對(duì)矩陣遍歷時(shí)能進(jìn)入多少次搜索,就代表有多少個(gè)島嶼。 Number of Islands 最新更新的思路,以及題II的解法請(qǐng)?jiān)L問(wèn):https://yanjia.me/zh/2018/11/... Given a 2d grid map of 1s (land) and 0s (water), count the nu...
摘要:兩個(gè)循環(huán)遍歷整個(gè)矩陣,出現(xiàn)則將其周圍相鄰的全部標(biāo)記為,用子函數(shù)遞歸標(biāo)記。注意里每次遞歸都要判斷邊界。寫一個(gè)的,寫熟練。 Number of Islands Problem Given a boolean/char 2D matrix, find the number of islands. 0 is represented as the sea, 1 is represented as...
Problem Given a non-empty 2D array grid of 0s and 1s, an island is a group of 1s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are s...
摘要:題目要求提供一個(gè)二維數(shù)組表示一張地圖,其中代表陸地,代表海洋。這里使用一個(gè)新的二維數(shù)組來(lái)表示對(duì)應(yīng)地圖上的元素屬于哪個(gè)并查集。在合并的時(shí)候先進(jìn)行判斷,如果二者為已經(jīng)相連的陸地,則無(wú)需合并,否則將新的二維數(shù)組上的元素指向所在的并查集。 題目要求 Given a 2d grid map of 1s (land) and 0s (water), count the number of isla...
摘要:在線網(wǎng)站地址我的微信公眾號(hào)完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個(gè)題。這是項(xiàng)目地址歡迎一起交流學(xué)習(xí)。 這篇文章記錄我練習(xí)的 LeetCode 題目,語(yǔ)言 JavaScript。 在線網(wǎng)站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號(hào): showImg(htt...
閱讀 705·2023-04-25 22:50
閱讀 1535·2021-10-08 10:05
閱讀 988·2021-09-30 09:47
閱讀 1925·2021-09-28 09:35
閱讀 827·2021-09-26 09:55
閱讀 3420·2021-09-10 10:51
閱讀 3433·2021-09-02 15:15
閱讀 3300·2021-08-05 09:57