leetcode-number-of-islands 发表于 2016-12-07 | 分类于 算法 , leetcode | 题目大意 https://leetcode.com/problems/number-of-islands/ 01矩阵中“小岛”的个数,所谓“小岛”指的是被0包围的1 题目分析 简单的BFS即可,DFS或者并查集也能做。 代码12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061public class Solution { private boolean[] v; private int ans; private boolean check(char[][] grid, int x, int y) { int row = grid.length; int col = grid[0].length; return x >= 0 && x <= row - 1 && y >= 0 && y <= col - 1; } private void bfs(char[][] grid, int x, int y) { int row = grid.length; int col = grid[0].length; int[] q = new int[row * col]; q[0] = x * col + y; v[x * col + y] = true; int front = 0; int rear = 1; while (front < rear) { int cur = q[front++]; int i = cur / col; int j = cur % col; for (int dy = -1; dy <= 1; dy += 2) { int tmp = i * col + j + dy; if (check(grid, i, j + dy) && !v[tmp] && grid[i][j + dy] == '1') { v[tmp] = true; q[rear++] = tmp; } } for (int dx = -1; dx <= 1; dx += 2) { int tmp = (i + dx) * col + j; if (check(grid, i + dx, j) && !v[tmp] && grid[i + dx][j] == '1') { v[tmp] = true; q[rear++] = tmp; } } } } public int numIslands(char[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == 0) { return 0; } int row = grid.length; int col = grid[0].length; v = new boolean[row * col]; ans = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (!v[i * col + j] && grid[i][j] == '1') { ans++; bfs(grid, i, j); } } } return ans; }} 时间复杂度:O(n*m)