每天一道LeetCode-----给定二维数组代表海域和岛屿,计算有多少个孤岛
生活随笔
收集整理的這篇文章主要介紹了
每天一道LeetCode-----给定二维数组代表海域和岛屿,计算有多少个孤岛
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Number of Islands
原題鏈接Number of Islands
給定一個(gè)二位數(shù)組,其中’0’代表水,’1’代表土地,判斷有多少個(gè)孤島被水隔開。假定二位數(shù)組四周都是’0’
思路:
遇到一個(gè)’1’就代表肯定有孤島,然后從這個(gè)位置開始將所有相鄰的’1’都變?yōu)椤?’
代碼如下
class Solution { public:int numIslands(vector<vector<char>>& grid) {int n = 0;for(int i = 0; i < grid.size(); ++i){for(int j = 0; j < grid[i].size(); ++j){if(grid[i][j] == '1'){++n;convert_to_zero(grid, i, j);}}}return n;} private:void convert_to_zero(vector<vector<char>>& grid, int i, int j){if(grid[i][j] == '0')return;grid[i][j] = '0';for(auto& dir : dirs){int row = i + dir[0];int col = j + dir[1];if(row < 0 || row >= grid.size() || col < 0 || col >= grid[row].size())continue;convert_to_zero(grid, row, col);}}static vector<vector<char>> dirs; };vector<vector<char>> Solution::dirs = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };總結(jié)
以上是生活随笔為你收集整理的每天一道LeetCode-----给定二维数组代表海域和岛屿,计算有多少个孤岛的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TCP/IP学习笔记(八)复位报文段
- 下一篇: TCP/IP学习笔记(九)TCP报文段首