200. Number of Islands

1, 如果加上斜的也可以。dfs加四种情况
dfs(grid,i-1,j-1);
dfs(grid,i+1,j+1);
dfs(grid,i-1,j+1);
dfs(grid,i+1,j-1);
2, 不让改变原有的input,我就说那就建一个相同size的2d boolean array。
或者visited[][]设成global
3, 转换为union find或者bfs,bfs解法:https://discuss.leetcode.com/topic/12230/c-bfs-solution-may-help-you
4, dfs,有可能stack overflow

public class Solution {
    
    private int m;
    private int n;
    private char[][] visit;
    public int numIslands(char[][] grid) {
        int count=0;
        m=grid.length;
        if(m==0) return 0;
        n=grid[0].length;
        visit=new char[m][n];
        for(int i=0;i=m||j>=n||grid[i][j]=='0') return;
        grid[i][j]='0';
        dfs(grid,i,j+1);
        dfs(grid,i,j-1);
        dfs(grid,i+1,j);
        dfs(grid,i-1,j);
    }
}

public class Solution {
    
    private int m;
    private int n;
    
    public int numIslands(char[][] grid) {
        int count=0;
        m=grid.length;
        if(m==0) return 0;
        n=grid[0].length;
        boolean[][] bool=new boolean[m][n];
        for(int i=0;i=m||j>=n||bool[i][j]==true) return;
        bool[i][j]=true;
        dfs(grid,i,j+1,bool);
        dfs(grid,i,j-1,bool);
        dfs(grid,i+1,j,bool);
        dfs(grid,i-1,j,bool);
    }
}

public class Solution {
    
    private int m;
    private int n;
    
    public int numIslands(char[][] grid) {
        int count=0;
        m=grid.length;
        if(m==0) return 0;
        n=grid[0].length;
        for(int i=0;i=m||j>=n||grid[i][j]=='0') return;
        grid[i][j]='0';
        dfs(grid,i,j+1);
        dfs(grid,i,j-1);
        dfs(grid,i+1,j);
        dfs(grid,i-1,j);
    }
}

你可能感兴趣的:(200. Number of Islands)