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:spa
11000 11000 00100 00011
Answer: 3.net
給定的一個二維網格的地圖(’1’(陸地)和0(水)),計數島的數量。島嶼是四面環水,是由相鄰的陸地水平或垂直鏈接而造成的。你能夠假設該網格的全部四個邊都被水包圍。code
一個網格,有一個相應的訪問標記矩陣,對網格每一個元素時行廣度優先遍歷(或者深度優先遍歷),統計島的數目orm
算法實現類get
public class Solution { public int numIslands(char[][] grid) { // 參數校驗 if (grid == null || grid.length == 0 || grid[0].length == 0) { return 0; } // 元素默認值是false boolean[][] visited = new boolean[grid.length][grid[0].length]; int result = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { // 若是此位置沒有被訪問過,而且此位置是島,就裏德廣度優先遍歷 if (!visited[i][j] && grid[i][j] == '1') { result++; bfs(grid, visited, i, j); } } } return result; } /** * 廣度優先搜索 * @param grid 網格 * @param visited 訪問標記矩陣 * @param row 橫座標 * @param col 縱座標 */ private void bfs(char[][] grid, boolean[][] visited, int row, int col) { if (row >= 0 && row < grid.length // 行合法 && col >= 0 && col < grid[0].length // 列合法 && !visited[row][col] // 沒有訪問過 && grid[row][col] == '1') { // 是島上陸地 // 標記此位置已經訪問過了 visited[row][col] = true; // 上 bfs(grid, visited, row - 1, col); // 右 bfs(grid, visited, row, col + 1); // 下 bfs(grid, visited, row + 1, col); // 左 bfs(grid, visited, row, col - 1); } } }