Skip to content

Commit

Permalink
fix graph cheatsheet
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Sep 30, 2023
1 parent 8afc429 commit bdce593
Showing 1 changed file with 62 additions and 58 deletions.
120 changes: 62 additions & 58 deletions doc/cheatsheet/graph.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,80 +57,84 @@


#### 1-1-1) Number of Distinct Islands
- LC 694
```java
// java
void dfs(char[][] grid, int r, int c){
int nr = grid.length;
int nc = grid[0].length;

if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') {
return;
}

grid[r][c] = '0';
- LC 694

```java
// java
void dfs(char[][] grid, int r, int c){
int nr = grid.length;
int nc = grid[0].length;

/** NOTE here !!!*/
dfs_1(grid, r - 1, c);
dfs_1(grid, r + 1, c);
dfs_1(grid, r, c - 1);
dfs_1(grid, r, c + 1);
if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') {
return;
}

public int numIslands_1(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
grid[r][c] = '0';

/** NOTE here !!!*/
dfs_1(grid, r - 1, c);
dfs_1(grid, r + 1, c);
dfs_1(grid, r, c - 1);
dfs_1(grid, r, c + 1);
}

public int numIslands_1(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}

int nr = grid.length;
int nc = grid[0].length;
int num_islands = 0;
int nr = grid.length;
int nc = grid[0].length;
int num_islands = 0;

for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
if (grid[r][c] == '1') {
++num_islands;
dfs_1(grid, r, c);
}
for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
if (grid[r][c] == '1') {
++num_islands;
dfs_1(grid, r, c);
}
}

return num_islands;
}

```
return num_islands;
}

```


#### 1-1-2) Max Area of Island
- LC 695
```java
// java
int[][] grid;
boolean[][] seen;

public int area(int r, int c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length ||
seen[r][c] || grid[r][c] == 0)
return 0;
seen[r][c] = true;
/** NOTE !!!*/
return (1 + area(r+1, c) + area(r-1, c)
+ area(r, c-1) + area(r, c+1));
}

public int maxAreaOfIsland_1(int[][] grid) {
this.grid = grid;
seen = new boolean[grid.length][grid[0].length];
int ans = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
ans = Math.max(ans, area(r, c));
}
- LC 695

```java
// java
int[][] grid;
boolean[][] seen;

public int area(int r, int c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length ||
seen[r][c] || grid[r][c] == 0)
return 0;
seen[r][c] = true;

/** NOTE !!!*/
return (1 + area(r+1, c) + area(r-1, c)
+ area(r, c-1) + area(r, c+1));
}

public int maxAreaOfIsland_1(int[][] grid) {
this.grid = grid;
seen = new boolean[grid.length][grid[0].length];
int ans = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
ans = Math.max(ans, area(r, c));
}
return ans;
}
```
return ans;
}
```

## 2) LC Example

Expand Down

0 comments on commit bdce593

Please sign in to comment.