200. Number of Islands
Posted
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: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3
bfs : 不使用visited 数组 则将其
思路很简单,遍历矩阵数联通的1块, 结果增, 防止再次遍历矩阵时重复将数过的1标记或转化为‘0‘ 或 ‘2‘
public class Solution { int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public int numIslands(char[][] grid) { if (grid == null || grid.length == 0) { return 0; } int m = grid.length; int n = grid[0].length; //boolean[][] visited = new boolean[m][n]; int ans = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] != ‘1‘) { continue; } // true; grid[i][j] = ‘2‘; bfs(grid, new int[]{i, j}); ans++; } } return ans; } private void bfs(char[][] grid, int[] cell) { int m = grid.length; int n = grid[0].length; Queue<int[]> q = new LinkedList<>(); q.offer(cell); while (!q.isEmpty()) { int[] cur = q.poll(); for (int[] dir : dirs) { int x = dir[0] + cur[0]; int y = dir[1] + cur[1]; if (x >= m || x < 0 || y >= n || y < 0 || grid[x][y] != ‘1‘) { continue; } grid[x][y] = ‘2‘; q.offer(new int[]{x, y}); } } } }
dfs
把入队改成自调用就ok了
int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public int numIslands(char[][] grid) { if (grid == null || grid.length == 0) { return 0; } int m = grid.length; int n = grid[0].length; //boolean[][] visited = new boolean[m][n]; int ans = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] != ‘1‘) { continue; } // true; grid[i][j] = ‘0‘; bfs(grid, new int[]{i, j}); ans++; } } return ans; } private void bfs(char[][] grid, int[] cell) { int m = grid.length; int n = grid[0].length; for (int[] dir : dirs) { int x = dir[0] + cell[0]; int y = dir[1] + cell[1]; if (x >= m || x < 0 || y >= n || y < 0 || grid[x][y] != ‘1‘) { continue; } grid[x][y] = ‘0‘; dfs(grid, new int[]{x, y}); } }
和529. Minesweeper不同是因为529只是根据一个输入值找到以此的全部路径, 而此时是矩阵所有的点都可能为起点
以上是关于200. Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章