/**
* 二维网格的行数和列数
*/
private int rowSize, colSize;
/**
* 从当前位置进行DFS,如果当前位置为陆地,则将它以及跟他它相连的陆地都改为水
*
* @param grid
* @param row
* @param col
*/
private void dfs(char[][] grid, int row, int col) {
if (row < 0 || row >= rowSize || col < 0 || col >= colSize || grid[row][col] == '0') {
return;
}
grid[row][col] = '0'; // 将陆地改为水,防止重复遍历
dfs(grid, row - 1, col); // 按顺时针方向dfs当前陆地的四周
dfs(grid, row, col + 1);
dfs(grid, row + 1, col);
dfs(grid, row, col - 1);
}
/**
* 法一(DFS)
*
* @param grid
* @return
*/
public int numIslands(char[][] grid) {
int landNum = 0;
rowSize = grid.length;
colSize = grid[0].length;
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < colSize; col++) {
if (grid[row][col] == '1') { // 从陆地开始
dfs(grid, row, col);
landNum++;
}
}
}
return landNum;
}
/**
* 二维网格的行数和列数
*/
private int rowSize, colSize;
/**
* BFS过程中用到变量
*/
private int dirs[][] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // 定义4个方向的row、col的增量
private Queue<Pair> queue = new LinkedList<>(); // 队列中存储当前位置的坐标
/**
* 坐标静态内部类
*/
private static class Pair {
private int row, col;
private Pair(int row, int col) {
this.row = row;
this.col = col;
}
}
/**
* 从当前位置进行BFS,如果当前位置为陆地,则将它以及跟他它相连的陆地都改为水
*
* @param grid
*/
private void bfs(char[][] grid) {
while (!queue.isEmpty()) {
Pair now = queue.poll();
for (int[] dir : dirs) { // 按顺时针方向bfs当前陆地的四周
int nextRow = dir[0] + now.row;
int nextCol = dir[1] + now.col;
if (nextRow >= 0 && nextRow < rowSize && nextCol >= 0 && nextCol < colSize && grid[nextRow][nextCol] == '1') {
grid[nextRow][nextCol] = '0'; // 将陆地改为水,防止重复遍历
queue.offer(new Pair(nextRow, nextCol));
}
}
}
}
/**
* 法二(BFS)
*
* @param grid
* @return
*/
public int numIslands_2(char[][] grid) {
int landNum = 0;
rowSize = grid.length;
colSize = grid[0].length;
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < colSize; col++) {
if (grid[row][col] == '1') { // 从陆地开始
queue.offer(new Pair(row, col)); // 起点入队列
bfs(grid);
landNum++;
}
}
}
return landNum;
}
/**
* 200. 岛屿数量
*/
lay.showTitle(200);
Solution200 sol200 = new Solution200();
char[][] grid200_1 = new char[][]{{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}};
char[][] grid200_2 = new char[][]{{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}};
arrayOpt.showCharTwoDimArray(grid200_1, grid200_1.length);
System.out.println(sol200.numIslands(grid200_1));
System.out.println(sol200.numIslands_2(grid200_2));
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- hzar.cn 版权所有 赣ICP备2024042791号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务