Graph
27. 542. 01 Matrix
class Solution {
public int[][] updateMatrix(int[][] mat) {
return bfs(mat);
}
private int[][] bfs(int[][] mat) {
int r = mat.length, c = mat[0].length;
Queue<int[]> q = new ArrayDeque<>();
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (mat[i][j] == 0)
q.offer(new int[] {i, j});
else
mat[i][j] = -1;
}
}
int[] directions = new int[] {-1, 0, 1, 0, -1};
while(q.size() > 0) {
int[] curr = q.poll();
int m = curr[0], n = curr[1];
for (int k = 0; k < 4; k++) {
int nm = m + directions[k], nn = n + directions[k+1];
if (nm < 0 || nm == r || nn < 0 || nn == c || mat[nm][nn] != -1)
continue;
mat[nm][nn] = mat[m][n] + 1;
q.offer(new int[] {nm, nn});
}
}
return mat;
}
private int[][] dp(int[][] mat) {
int r = mat.length, c = mat[0].length, INF = r + c;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (mat[i][j] == 0) continue;
int top = INF, left = INF;
if (i - 1 >= 0) top = mat[i - 1][j];
if (j - 1 >= 0) left = mat[i][j - 1];
mat[i][j] = Math.min(top, left) + 1;
}
}
for (int i = r - 1; i >= 0; i--) {
for (int j = c - 1; j >= 0; j--) {
if (mat[i][j] == 0) continue;
int bottom = INF, right = INF;
if (i + 1 < r) bottom = mat[i + 1][j];
if (j + 1 < c) right = mat[i][j + 1];
mat[i][j] = Math.min(mat[i][j], Math.min(bottom, right) + 1);
}
}
return mat;
}
}28. 133. Clone Graph
LeetCode 207 & 210: Course Schedule I & II | Topological Sort | Kahn's algorithm
union search / disjoint set / BFS
DFS / recursive
Note that in Graph BFS, compared with Tree BFS, we need to mark the visited node as visited to prevent infinite loop.
32. Accounts Merge
TODO
33. 127. Word Ladder
34. Word Search
TODO
Last updated
Was this helpful?