标签:nes == min color cal round www dir 标记
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}); } }
标签:nes == min color cal round www dir 标记
原文地址:http://www.cnblogs.com/apanda009/p/7289639.html