国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 蕲春县| 富锦市| 张家界市| 拜城县| 库伦旗| 海晏县| 吉隆县| 宜丰县| 兴城市| 北海市| 民乐县| 长治县| 桦川县| 平度市| 当阳市| 佛山市| 万年县| 靖边县| 会泽县| 横峰县| 房产| 韶关市| 德格县| 灵宝市| 宁城县| 高阳县| 葵青区| 丰原市| 维西| 河曲县| 兴仁县| 察隅县| 刚察县| 琼海市| 公安县| 尖扎县| 石嘴山市| 新安县| 买车| 台北市| 阿图什市|