Thursday, January 5, 2017

Leetcode/各大家 -- 200. Number of Islands(back tracking)

200. Number of Islands(back tracking)
  • Difficulty: Medium
https://leetcode.com/problems/number-of-islands/
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

相关题: http://rainykat.blogspot.com/2017/01/leetcodegf-286-walls-and-gates.html

思路: Use dfs when meeting '1',count the land recursively at 4 surrounding pos and sink make '1' to '0'. 
Complexity: dfs: worst space,time is O(row*col) or O(m*n) grid row length be m, grid col length as n
关键字: Backtracking

public class Solution {
    public int numIslands(char[][] grid) {
        int count =0;
        for (int i = 0; i < grid.length; i++)
            for (int j = 0; j < grid[0].length; j++)
                if (grid[i][j] == '1'){
                    count+=dfs(grid, i, j);//clearRestOfLand(
                }
        
        return count;
    }

    private int dfs(char[][] grid, int i, int j) {
        if(i<0||i>=grid.length||j>=grid[0].length||j<0||grid[i][j]=='0') return 0;
        grid[i][j]='0';//sink land, '1' to '0'
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
        return 1;
    }
}

No comments:

Post a Comment