【LeetCode 剑指offer刷题】回溯法与暴力枚举法题6:Number of Islands
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode 剑指offer刷题】回溯法与暴力枚举法题6:Number of Islands
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
【LeetCode & 劍指offer 刷題筆記】目錄(持續(xù)更新中...)
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: 3C++ 類似題目: 13 機(jī)器人的運(yùn)動(dòng)范圍? Word Search(系列) ?? ?這道求島嶼數(shù)量的題的本質(zhì)是求矩陣中連續(xù)區(qū)域的個(gè)數(shù),很容易想到需要用深度優(yōu)先搜索DFS來解,我們需要建立一個(gè)visited數(shù)組用來記錄某個(gè)位置是否被訪問過, ?? ?對(duì)于一個(gè)為‘1’且未被訪問過的位置,我們遞歸進(jìn)入其上下左右位置上為‘1’的數(shù),將其visited對(duì)應(yīng)值賦為true,繼續(xù)進(jìn)入其所有相連的鄰位置,這樣可以將這個(gè)連通區(qū)域所有的數(shù)找出來,并將其對(duì)應(yīng)的visited中的值賦true, ?? ?找完次區(qū)域后,我們將結(jié)果res自增1,然后我們?cè)诶^續(xù)找下一個(gè)為‘1’且未被訪問過的位置,以此類推直至遍歷完整個(gè)原數(shù)組即可得到最終結(jié)果,代碼如下: class Solution { public: ??? int numIslands(vector<vector<char> > &grid) ??? { ??????? if (grid.empty() || grid[0].empty()) return 0; ??????? ??????? int m = grid.size(), n = grid[0].size(); ??????? int result = 0; ??????? vector<vector<bool> > visited(m, vector<bool>(n, false)); //創(chuàng)建訪問矩陣 ??????? for (int i = 0; i < m; i++)?//遍歷柵格中所有元素(因?yàn)槊總€(gè)點(diǎn)都有可能為某個(gè)島嶼的某點(diǎn)) ??????? { ??????????? for (int j = 0; j < n; j++) ??????????? { ??????????????? if (grid[i][j] == '1' && !visited[i][j]) { ??????????????????? numIslandsDFS(grid, visited, i, j); //向相鄰方向(上下左右)走當(dāng)遇到越界,或者遇到0或者遇到訪問過的1后,遞歸函數(shù)退出,所有遞歸分支退出后,該遞歸函數(shù)結(jié)束,找到一個(gè)島嶼 ??????????????????? result++; //統(tǒng)計(jì)島嶼的個(gè)數(shù) ??????????????? } ??????????? } ??????? } ??????? return result; ??? } ??? void numIslandsDFS(vector<vector<char> > &grid, vector<vector<bool> > &visited, int x, int y) { ??????? if (x < 0 || x >= grid.size()) return; ??????? if (y < 0 || y >= grid[0].size()) return; //超出范圍時(shí)退出 ??????? if (grid[x][y] != '1' || visited[x][y]) return; //如果不為1或者訪問過就退出 ??????? ??????? visited[x][y] = true; ??????? numIslandsDFS(grid, visited, x - 1, y); ??????? numIslandsDFS(grid, visited, x + 1, y); ??????? numIslandsDFS(grid, visited, x, y - 1); ??????? numIslandsDFS(grid, visited, x, y + 1); ??? } }; 轉(zhuǎn)自:https://www.cnblogs.com/grandyang/p/4402656.html
?
轉(zhuǎn)載于:https://www.cnblogs.com/wikiwen/p/10229466.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的【LeetCode 剑指offer刷题】回溯法与暴力枚举法题6:Number of Islands的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET Core 实战:使用 N
- 下一篇: 《追风行动》有点儿意思