2024/9/3 Hot100 graph
This commit is contained in:
parent
9cadfd058d
commit
af0ac3a040
|
@ -0,0 +1,45 @@
|
||||||
|
package com.cool.hot100.graph;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created with IntelliJ IDEA.
|
||||||
|
*
|
||||||
|
* @Author: Cool
|
||||||
|
* @Date: 2024/09/03/11:24
|
||||||
|
* DayNumber 2
|
||||||
|
* Hard 2
|
||||||
|
* Level ?
|
||||||
|
*/
|
||||||
|
|
||||||
|
public class Num200 {
|
||||||
|
|
||||||
|
public int numIslands(char[][] grid) {
|
||||||
|
int res = 0;
|
||||||
|
for (int i = 0; i < grid.length; i++) {
|
||||||
|
for (int j = 0; j < grid[i].length; j++) {
|
||||||
|
if (grid[i][j] == '1') {
|
||||||
|
res++;
|
||||||
|
dfs(grid, i, j);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void dfs(char[][] grid, int x, int y) {
|
||||||
|
if (!isInArea(grid, x, y)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (grid[x][y] != '1') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
grid[x][y] = '2';
|
||||||
|
dfs(grid, x + 1, y);
|
||||||
|
dfs(grid, x, y + 1);
|
||||||
|
dfs(grid, x, y - 1);
|
||||||
|
dfs(grid, x - 1, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isInArea(char[][] grid, int x, int y) {
|
||||||
|
return x >= 0 && y >= 0 && x < grid.length && y < grid[0].length;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue