Skip to content

Commit

Permalink
add code comment, update graph cheatsheet
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Sep 30, 2023
1 parent 2c49be7 commit 8afc429
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
77 changes: 77 additions & 0 deletions doc/cheatsheet/graph.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,83 @@
- longest_path
- is_cycle


#### 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';

/** 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;

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;
}

```


#### 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));
}
}
return ans;
}
```

## 2) LC Example

### 2-1) Closest Leaf in a Binary Tree
Expand Down
1 change: 1 addition & 0 deletions leetcode_java/src/main/java/LeetCodeJava/DFS/PathSum.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

public class PathSum {

// V0
public boolean hasPathSum(TreeNode root, int targetSum) {

if (root == null){
Expand Down

0 comments on commit 8afc429

Please sign in to comment.