200. Number of Islands | Java最短代码实现

原题链接: 200. Number of Islands

【思路】

本题考查dfs和bfs的结合。由于题目没有限制不可改变原数组的结构,所以一旦遇到1,就将周边相邻的几个1置为2。遍历整个数组,遇到1的个数要求的解:

    public int numIslands(char[][] grid) {
        int islansNum = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] != '1') continue;
                dfs(grid, i, j);
                islansNum++;
            }
        }
        return islansNum;
    }
    public void dfs(char[][] grid, int row, int column) {
        if (row >= 0 && row < grid.length 
            && column >= 0 && column < grid[0].length) {
                    if (grid[row][column] == '1') {
                        grid[row][column] = '2';
                        dfs(grid, row + 1, column);
                        dfs(grid, row, column + 1);
                        dfs(grid, row - 1, column);
                        dfs(grid, row, column - 1);
                    }
            }
    }
45 / 45  test cases passed. Runtime: 4 ms  Your runtime beats 37.40% of javasubmissions.
欢迎优化!

你可能感兴趣的:(DFS,bfs)