200Number of Islands

来源:互联网 发布:怎么变成大小为1矩阵 编辑:程序博客网 时间:2024/05/16 04:41

题目链接: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:11110110101100000000Answer: 1Example 2:11000110000010000011Answer: 3

解题思路:
这题的考点是图的遍历(深度优先遍历或广度优先遍历)。
搞清楚考点后就很容易解题了。
1. 按行优先的顺序遍历网格。
2. 每次遇到字符为 1 的网格,count ++
3. 同时使用图的深度优先搜索遍历,将其本身以及和其关联的所有字符为 1 的网格都赋值为 2(一个不为 1 的字符即可,起到区分已遍历的作用)。
4. 这种解法有个弊端,就是破坏了原本的数组。

代码实现:

public class Solution {    public int numIslands(char[][] grid) {        if(grid == null || grid.length == 0 || grid[0].length == 0)            return 0;        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 ++;                    traverse(grid, i, j);                }            }        }        return count;    }    void traverse(char[][] grid, int i, int j) { // DFS        grid[i][j] = '2';        if(i > 0 && grid[i - 1][j] == '1')            traverse(grid, i - 1, j);        if(i < grid.length - 1 && grid[i + 1][j] == '1')            traverse(grid, i + 1, j);        if(j > 0 && grid[i][j - 1] == '1')            traverse(grid, i, j - 1);        if(j < grid[0].length - 1 && grid[i][j + 1] == '1')            traverse(grid, i, j + 1);    }}
45 / 45 test cases passed.Status: AcceptedRuntime: 3 ms
0 0