-
Notifications
You must be signed in to change notification settings - Fork 2
/
MainLandQuestion
83 lines (75 loc) · 2.42 KB
/
MainLandQuestion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package org.example;
import java.util.LinkedList;
import java.util.Queue;
public class MainLandQuestion {
private int[][] directions={{-1,0},{1,0},{0,-1},{0,1}};
public static void main(String[] args){
MainLandQuestion mainLandBFS=new MainLandQuestion();
char[][] grid1 = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}
};
System.out.println(mainLandBFS.resolve(grid1));
}
public int resolve(char[][] grid){
int rows=grid.length;
int cols=grid[0].length;
int mainlandCount=0;
boolean[][] visited=new boolean[rows][cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(!visited[i][j]&&grid[i][j]=='1'){
mainlandCount+=1;
bfs(grid,i,j,visited);
}
}
}
return mainlandCount;
}
/**
* 深度优先遍历图
* @param grid
* @param row
* @param col
* @param visited
*/
public void bfs(char[][] grid,int row,int col,boolean[][] visited){
int rows=grid.length;
int cols=grid[0].length;
Queue<int[]> list=new LinkedList<>();
list.offer(new int[]{row,col});
while (!list.isEmpty()){
int[] current=list.poll();
int currentRow=current[0];
int currentCol=current[1];
for(int[] direction:directions){
int nextNodeRow=direction[0]+currentRow;
int nextNodeCol=direction[1]+currentCol;
if(nextNodeRow>=0&&nextNodeRow<rows&&nextNodeCol>=0&&nextNodeCol<cols&&grid[nextNodeRow][nextNodeCol]=='1'&&visited[nextNodeRow][nextNodeCol]==false){
list.add(new int[]{nextNodeRow,nextNodeCol});
visited[nextNodeRow][nextNodeCol]=true;
}
}
}
}
/**
* 深度优先遍历图
* @param grid
* @param row
* @param col
*/
public void dfs(char[][] grid, int row, int col) {
int m = grid.length;
int n = grid[0].length;
if (row < 0 || row >= m || col < 0 || col >= n || grid[row][col] == '0') {
return;
}
grid[row][col] = '0';
dfs(grid, row - 1, col);
dfs(grid, row + 1, col);
dfs(grid, row, col - 1);
dfs(grid, row, col + 1);
}
}