标签:就是 同方 span 作用 cal count lan sea isl
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: 3
第一次用DFS,基本思路就是遍历表中的每一个元素,将‘1’标记为‘0’,同时访问它上下左右的元素并且逐个标记为零,每访问一个元素,首先访问该元素的相邻,不停地deep search下去,然后再一级一级向上返回,返回上一个元素的不同方向的元素。
class Solution { int m; //这里一定要用全局变量,不然DFSMarking里面的m和n不起作用 int n; public int numIslands(char[][] grid) { n = grid.length; if(n == 0) return 0; m = grid[0].length; int count = 0; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(grid[i][j] == ‘1‘){ DFSMarking(grid, i, j); count++; } } } return count; } public void DFSMarking(char[][] grid, int i, int j) { if(i<0 || j<0 || i>n-1 || j>m-1 || grid[i][j] != ‘1‘) return; grid[i][j] = ‘0‘; DFSMarking(grid,i+1,j); DFSMarking(grid,i-1,j); DFSMarking(grid,i,j+1); DFSMarking(grid,i,j-1); } }
leetcode 200. Number of Islands
标签:就是 同方 span 作用 cal count lan sea isl
原文地址:https://www.cnblogs.com/jamieliu/p/10331654.html