200. 岛屿数量
题目:
思路:
【1】可以参考 剑指 Offer II 105. 岛屿的最大面积(695. 岛屿的最大面积) 这篇,本质上思路都是一样的
代码展示:
深度优先搜索:
//时间2 ms 击败 100% //内存46.3 MB 击败 81.86% class Solution { 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] == '1'){ num++; infect(i, j, grid); } } } return num; } public static void infect(int x, int y, char[][] grid){ //限制条件(首先是上下左右边界,其次是小岛土地判断) if(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == '0'){ return; } if(grid[x][y] == '1'){ //这里是将岛屿遍历完后变为海域,防止二次遍历 grid[x][y] = '0'; } infect(x - 1, y, grid); infect(x + 1, y, grid); infect(x, y - 1, grid); infect(x, y + 1, grid); } }
广度优先搜索:
//时间30 ms 击败 6.71% //内存52.5 MB 击败 5.2% class Solution { public int numIslands(char[][] grid) { int ans = 0; for (int i = 0; i != grid.length; ++i) { for (int j = 0; j != grid[0].length; ++j) { Queue<Integer> queuei = new LinkedList<Integer>(); Queue<Integer> queuej = new LinkedList<Integer>(); queuei.offer(i); queuej.offer(j); if (grid[i][j] == '1') ans++; while (!queuei.isEmpty()) { int cur_i = queuei.poll(), cur_j = queuej.poll(); if (cur_i < 0 || cur_j < 0 || cur_i == grid.length || cur_j == grid[0].length || grid[cur_i][cur_j] != '1') { continue; } //这里将小岛变海域,防止二次遍历 grid[cur_i][cur_j] = '0'; int[] di = {0, 0, 1, -1}; int[] dj = {1, -1, 0, 0}; for (int index = 0; index != 4; ++index) { int next_i = cur_i + di[index], next_j = cur_j + dj[index]; queuei.offer(next_i); queuej.offer(next_j); } } } } return ans; } }