1. 程式人生 > >200 Number of Islands

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:

11110
11010
11000
00000
Answer: 1

Example 2
: 11000 11000 00100 00011 Answer: 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: Accepted
Runtime: 3 ms