200. Number of Islands
Posted clarencezzh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
这个题目可以使用bfs和dfs。
如果使用bfs,因为队列的时间复杂度太高了,可以使用stack代替。
class Coordinate { int x; int y; public Coordinate(int x, int y) { this.x = x; this.y = y; } } public int numIslands(char[][] grid) { int count = 0; int rows = grid.length; int cols = rows>0?grid[0].length:0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == ‘0‘) continue; Stack<Coordinate> queue = new Stack<>(); count++; queue.add(new Coordinate(i, j)); while (!queue.isEmpty()) { Coordinate coordinate = queue.pop(); int x = coordinate.x; int y = coordinate.y; grid[x][y] = ‘0‘; if (x + 1 < rows && grid[x + 1][y] != ‘0‘) { queue.add(new Coordinate(x + 1, y)); } if (y + 1 < cols && grid[x][y + 1] != ‘0‘) { queue.add(new Coordinate(x, y + 1)); } if (x - 1 >= 0 && grid[x - 1][y] != ‘0‘) { queue.add(new Coordinate(x - 1, y)); } if (y - 1 >= 0 && grid[x][y - 1] != ‘0‘) { queue.add(new Coordinate(x, y - 1)); } } } } return count; }
使用dfs递归完成后,是否需要恢复现场需要根据实际情况而定。
public class 岛屿的数量 { public int numIslands(char[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == 0) return 0; int rows = grid.length; int cols = grid[0].length; int count = 0; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) // 注意char if (grid[i][j] == ‘1‘) { count++; dfsSearch(grid, i, j, rows, cols); } return count++; } // 每遇到‘1‘后, 开始向四个方向 递归搜索. 搜到后变为‘0‘, // 因为相邻的属于一个island. 然后开始继续找下一个‘1‘. private void dfsSearch(char[][] grid, int i, int j, int rows, int cols) { if (i < 0 || i >= rows || j < 0 || j >= cols) return; if (grid[i][j] != ‘1‘) return; // 也可以才用一个visited数组,标记遍历过的岛屿 grid[i][j] = ‘0‘;//不需要恢复现场 dfsSearch(grid, i + 1, j, rows, cols); dfsSearch(grid, i - 1, j, rows, cols); dfsSearch(grid, i, j + 1, rows, cols); dfsSearch(grid, i, j - 1, rows, cols); } }
以上是关于200. Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章