国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

200. Number of Islands

2019-11-08 19:52:16
字體:
來源:轉載
供稿:網友

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: 11110 11010 11000 00000 Answer: 1

Example 2: 11000 11000 00100 00011 Answer: 3

解題思路:一刷ac,深度搜索講訪問過的節(jié)點重置。

public class Solution { public int numIslands(char[][] grid) { int res = 0; if (grid == null || grid.length == 0 || grid[0].length == 0) return res; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] == '1') { helper(grid, i, j); res++; } } } return res; } public void helper(char[][] grid, int row, int col) { if (row >= grid.length || col >= grid[0].length || row < 0 || col < 0 || grid[row][col] != '1') return; grid[row][col] = '0'; helper(grid, row+1, col); helper(grid, row-1, col); helper(grid, row, col+1); helper(grid, row, col-1); }}class Solution {public: int numIslands(vector<vector<char>>& grid) { if (grid.empty() || grid.size() == 0 || grid[0].size() == 0) return 0; int res = 0; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { if (grid[i][j] == '1'){ res++; helper(grid, i, j); } } } return res; } void helper(vector<vector<char>> & grid, int row, int col) { if (row < 0 || col < 0 || row >= grid.size() || col >= grid[0].size() || grid[row][col] != '1') return; grid[row][col] = '0'; helper(grid, row+1, col); helper(grid, row-1, col); helper(grid, row, col+1); helper(grid, row, col-1); }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 四平市| 尤溪县| 城市| 城口县| 河源市| 沙洋县| 德昌县| 关岭| 类乌齐县| 聂拉木县| 永平县| 娄底市| 镇赉县| 洱源县| 龙口市| 景谷| 明溪县| 乌兰察布市| 武隆县| 女性| 禄劝| 密云县| 桂阳县| 昆明市| 长宁县| 景洪市| 伊金霍洛旗| 织金县| 开封市| 马鞍山市| 双柏县| 邹城市| 贵港市| 林西县| 博客| 黄梅县| 高安市| 稷山县| 昂仁县| 十堰市| 临颍县|