[LeetCode] 200. 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:

11110110101100000000

Answer: 1

Example 2:

11000110000010000011

Answer: 3

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

本质是求矩阵中连续区域的个数, 可以用BFS, DFS, 或者 Union Find来解。

Java: BFS

class Coordinate {
    int x, y;
    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Solution {
    public int numIslands(boolean[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }

        int n = grid.length;
        int m = grid[0].length;
        int islands = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j]) {
                    markByBFS(grid, i, j);
                    islands++;
                }
            }
        }

        return islands;
    }

    private void markByBFS(boolean[][] grid, int x, int y) {
        int[] directionX = {0, 1, -1, 0};
        int[] directionY = {1, 0, 0, -1};
        Queue<Coordinate> queue = new LinkedList<>();
        queue.offer(new Coordinate(x, y));
        grid[x][y] = false;

        while (!queue.isEmpty()) {
            Coordinate coor = queue.poll();
            for (int i = 0; i < 4; i++) {
                Coordinate adj = new Coordinate(
                    coor.x + directionX[i],
                    coor.y + directionY[i]
                );
                if (!inBound(adj, grid)) {
                    continue;
                }
                if (grid[adj.x][adj.y]) {
                    grid[adj.x][adj.y] = false;
                    queue.offer(adj);
                }
            }
        }
    }

    private boolean inBound(Coordinate coor, boolean[][] grid) {
        int n = grid.length;
        int m = grid[0].length;

        return coor.x >= 0 && coor.x < n && coor.y >= 0 && coor.y < m;
    }
}

Java: DFS

public class Solution {
    private int m, n;
    public void dfs(boolean[][] grid, int i, int j) {
        if (i < 0 || i >= m || j < 0 || j >= n) return;

        if (grid[i][j]) {
            grid[i][j] = false;
            dfs(grid, i - 1, j);
            dfs(grid, i + 1, j);
            dfs(grid, i, j - 1);
            dfs(grid, i, j + 1);
        }
    }

    public int numIslands(boolean[][] grid) {
        m = grid.length;
        if (m == 0) return 0;
        n = grid[0].length;
        if (n == 0) return 0;

        int ans = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!grid[i][j]) continue;
                ans++;
                dfs(grid, i, j);
            }
        }
        return ans;
    }
}

Java: Union Find

class UnionFind {
    private int[] father = null;
    private int count;

    private int find(int x) {
        if (father[x] == x) {
            return x;
        }
        return father[x] = find(father[x]);
    }

    public UnionFind(int n) {
        // initialize your data structure here.
        father = new int[n];
        for (int i = 0; i < n; ++i) {
            father[i] = i;
        }
    }

    public void connect(int a, int b) {
        int root_a = find(a);
        int root_b = find(b);
        if (root_a != root_b) {
            father[root_a] = root_b;
            count --;
        }
    }

    public int query() {
        return count;
    }

    public void set_count(int total) {
        count = total;
    }
}

public class Solution {
    public int numIslands(boolean[][] grid) {
        int count = 0;
        int n = grid.length;
        if (n == 0)
            return 0;
        int m = grid[0].length;
        if (m == 0)
            return 0;
        UnionFind union_find = new UnionFind(n * m);

        int total = 0;
        for(int i = 0;i < grid.length; ++i)
            for(int j = 0;j < grid[0].length; ++j)
            if (grid[i][j])
                total ++;

        union_find.set_count(total);
        for(int i = 0;i < grid.length; ++i)
            for(int j = 0;j < grid[0].length; ++j)
            if (grid[i][j]) {
                if (i > 0 && grid[i - 1][j]) {
                    union_find.connect(i * m + j, (i - 1) * m + j);
                }
                if (i <  n - 1 && grid[i + 1][j]) {
                    union_find.connect(i * m + j, (i + 1) * m + j);
                }
                if (j > 0 && grid[i][j - 1]) {
                    union_find.connect(i * m + j, i * m + j - 1);
                }
                if (j < m - 1 && grid[i][j + 1]) {
                    union_find.connect(i * m + j, i * m + j + 1);
                }
            }
        return union_find.query();
    }
}

Python: BFS

class Solution:
    def numIslands(self, grid):
        m = len(grid)
        if m == 0:
            return 0
        n = len(grid[0])
        visit = [[False for i in range(n)]for j in range(m)]
        def check(x, y):
            if x >= 0 and x<m and y>= 0 and y< n and grid[x][y] and visit[x][y] == False:
                return True
        def bfs(x,y):
            nbrow = [1,0,-1,0]
            nbcol = [0,1,0,-1]
            q=[(x,y)]
            while len(q) > 0:
                x = q[0][0]
                y = q[0][1]
                q.pop(0)
                for k in range(4):
                    newx = x + nbrow[k]
                    newy = y + nbcol[k]
                    if check(newx, newy):
                        visit[newx][newy] = True
                        q.append((newx,newy))

        count = 0
        for row in range(m):
            for col in range(n):
                if check(row,col):
                    visit[row][col] = True
                    bfs(row,col)
                    count+=1
        return count

Python: DFS

class Solution:
    def numIslands(self, grid):
        if not grid:
            return 0

        row = len(grid)
        col = len(grid[0])
        count = 0
        for i in xrange(row):
            for j in xrange(col):
                if grid[i][j] == ‘1‘:
                    self.dfs(grid, row, col, i, j)
                    count += 1
        return count

    def dfs(self, grid, row, col, x, y):
        if grid[x][y] == ‘0‘:
            return
        grid[x][y] = ‘0‘

        if x != 0:
            self.dfs(grid, row, col, x - 1, y)
        if x != row - 1:
            self.dfs(grid, row, col, x + 1, y)
        if y != 0:
            self.dfs(grid, row, col, x, y - 1)
        if y != col - 1:
            self.dfs(grid, row, col, x, y + 1)

Python: DFS

class Solution:
    def numIslands(self, grid):
        m = len(grid)
        if m == 0:
            return 0
        n = len(grid[0])
        visit = [[False for i in range(n)]for j in range(m)]
        def check(x, y):
            if x >= 0 and x<m and y>= 0 and y< n and grid[x][y] and visit[x][y] == False:
                return True
        def dfs(x,y):
            nbrow = [1,0,-1,0]
            nbcol = [0,1,0,-1]
            for k in range(4):
                newx = x + nbrow[k]
                newy = y + nbcol[k]
                if check(newx, newy):
                    visit[newx][newy] = True
                    dfs(newx,newy)
        count = 0
        for row in range(m):
            for col in range(n):
                if check(row,col):
                    visit[row][col] = True
                    dfs(row,col)
                    count+=1
        return count

  

类似题目:

[LeetCode] 305. Number of Islands II 岛屿的数量之二

  

原文地址:https://www.cnblogs.com/lightwindy/p/8487025.html

时间: 2024-10-18 18:42:06

[LeetCode] 200. Number of Islands 岛屿的数量的相关文章

LeetCode | 0200. Number of Islands岛屿数量【Python】

LeetCode 0200. Number of Islands岛屿数量[Medium][Python][DFS] Problem LeetCode 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 v

[LintCode] Number of Islands 岛屿的数量

Given a boolean 2D matrix, find the number of islands. Notice 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent. Have you met this ques

200 Number of Islands 岛屿的个数

给定 '1'(陆地)和 '0'(水)的二维网格图,计算岛屿的数量.一个岛被水包围,并且通过水平或垂直连接相邻的陆地而形成.你可以假设网格的四个边均被水包围.示例 1:11110110101100000000答案: 1示例 2:11000110000010000011答案: 3 详见:https://leetcode.com/problems/number-of-islands/description/ class Solution { public: int numIslands(vector<

Leetcode 200. 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

[LeetCode] 200. 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

leetcode 200. Number of Islands(DFS)

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

&lt;LeetCode OJ&gt; 200. Number of Islands

Total Accepted: 48411 Total Submissions: 171609 Difficulty: Medium 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 verticall

【LeetCode】200. Number of Islands (2 solutions)

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

200. Number of Islands

https://leetcode.com/problems/number-of-islands/#/description 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. Yo