[Leetcode]Number of Island

来源:互联网 发布:mac如何删除文件夹 编辑:程序博客网 时间:2024/05/21 18:45

[题目]

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:

11110110101100000000

Answer: 1

Example 2:

11000110000010000011

Answer: 3


[思路]

对于grid里面遇到的“1”,利用DFS,进行搜索深入,只要是相连的,就挖出来变成0,好聪明啊。。。简直了哦。

[代码]

public class Solution {    private static final int[][] DIRS = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};    private static final char L = '1', W = '0';    public void dfsFill(char[][] g, int x, int y) {        if (x >= 0 && x < g.length && y >= 0 && y < g[0].length && g[x][y] == L) {            g[x][y] = W;            for (int[] d : DIRS) dfsFill(g, x + d[0], y + d[1]);        }    }    public int numIslands(char[][] grid) {        int num = 0;        for (int i = 0; i < grid.length; i++) {            for (int j = 0; j < grid[0].length; j++) {                if (grid[i][j] == L) {                    num++;                    dfsFill(grid, i, j);                }            }        }        return num;    }}


0 0
原创粉丝点击