首页 > 学院 > 开发设计 > 正文

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,深度搜索讲访问过的节点重置。

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); }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表