Java算法题之岛屿数量
题目描述:
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。
package NumberOfIslands;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0) {
return 0;
}
int numIslands = 0;
int x = grid.length;
int y = grid[0].length;
for(int i = 0 ; i < x ; i++) {
for(int j = 0 ; j < y ; j++) {
if(grid[i][j] == '1') {
numIslands++;
grid[i][j] = '0';
Queue<Integer> queue = new LinkedList<>();
queue.add(i * y + j);//存储该数字在数组中的位置
while (!queue.isEmpty()) {
int id = queue.remove();
int row = id / y;
int col = id % y;
if(row - 1 >= 0 && grid[row - 1][col] == '1') {
queue.add((row - 1) * y + col);
grid[row - 1][col] = '0';
}
if(row + 1 < x && grid[row + 1][col] == '1') {
queue.add((row + 1) * y + col);
grid[row + 1][col] = '0';
}
if(col - 1 >= 0 && grid[row][col - 1] == '1') {
queue.add(row * y + col - 1);
grid[row][col -1] = '0';
}
if(col + 1 < y && grid[row][col + 1] == '1') {
queue.add(row * y + col + 1);
grid[row][col + 1] = '0';
}
}
}
}
}
return numIslands;
}
}
package NumberOfIslands;
public class Client {
public static void main(String[] args) {
char[][] grid = {{'1','1','1'},{'0','1','0'},{'1','1','1'}};
Solution st = new Solution();
System.out.println(st.numIslands(grid));
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。