Skip to content

Commit d999e0d

Browse files
committed
LIVE_YOUTUBE - graphs and dp problem
1 parent fdd00b5 commit d999e0d

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

LeetCode/1306.jump-game3.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
vector<int> nums;
3+
set<int> s; // what all indices are there in recursion stack
4+
5+
bool isPossible(int cur) { // can we reach a zero from cur index
6+
if (s.find(cur) != s.end()) {
7+
return false; // we detected a cycle / deadlock
8+
}
9+
if(0 <= cur && cur < nums.size()) {
10+
if(nums[cur] == 0) return true;
11+
s.insert(cur);
12+
bool ans = false;
13+
if (isPossible(cur + nums[cur])) ans = true;
14+
else if (isPossible(cur - nums[cur])) ans = true;
15+
s.erase(cur);
16+
return ans;
17+
}
18+
return false;
19+
}
20+
public:
21+
bool canReach(vector<int>& arr, int start) {
22+
//dp[i] <-- is it possible to reach a zero from i
23+
nums = arr;
24+
return isPossible(start);
25+
}
26+
};

LeetCode/542.01-matrix.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
using loc = pair<int, int>;
2+
int dx[] = {1, -1, 0, 0};
3+
int dy[] = {0, 0, 1, -1};
4+
class Solution {
5+
public:
6+
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
7+
int n = mat.size(), m = mat[0].size();
8+
9+
vector<vector<int>> dis(n, vector<int>(m, INT_MAX));
10+
// dis[i][j] = nearest distance (i, j) to nearest 0
11+
12+
queue<loc> q;
13+
for(int i = 0; i < n; i++) {
14+
for(int j = 0; j < m; j++) {
15+
if (mat[i][j] == 0) {
16+
q.push({i, j});
17+
dis[i][j] = 0;
18+
}
19+
}
20+
}
21+
22+
while(!q.empty()) {
23+
// loc cur = q.front();
24+
// int x = cur.first, y = cur.second;
25+
auto [x, y] = q.front(); // current loc in mat, structured binding in C++
26+
q.pop();
27+
// (2,3) -> (1, 3) up, (3, 3) down, +1 -1 on the columns as well
28+
for(int k = 0; k < 4; k++) {
29+
int nx = x + dx[k], ny = y + dy[k];
30+
if (0 <= nx && nx < n && 0 <= ny && ny < m) {
31+
// valid neighbour
32+
if (dis[nx][ny] == INT_MAX) {
33+
dis[nx][ny] = 1 + dis[x][y];
34+
q.push({nx, ny});
35+
}
36+
}
37+
}
38+
}
39+
40+
return dis;
41+
}
42+
};
43+
44+
/*
45+
// BFS gives the shortest path in unweighted graphs
46+
47+
n * m <--- 0s and 1s
48+
49+
for every 1:
50+
compute the smallest distance to 0
51+
52+
dis[i][j] = 0 where mat[i][j] = 0
53+
54+
queue<> Q = {(i,j)} where mat[i][j] = 0;
55+
56+
cur = Q.front();
57+
58+
for(nei in neighbors(cur)) {
59+
dis[nei] = 1 + dis[cur] if nei is not alreaady in queue
60+
}
61+
62+
*/
63+

0 commit comments

Comments
 (0)