1
+ /*
2
+ * Problem: 542
3
+ * Name: 01 Matrix
4
+ * Difficulty: Medium
5
+ * Topic: Graphs
6
+ * Link: https://leetcode.com/problems/01-matrix
7
+ */
8
+
9
+ #include < bits/stdc++.h>
10
+ #include < queue>
11
+ using namespace std ;
12
+
13
+ // BFS (breadth first search)
14
+ // Time Complexity: O(m*n)
15
+ // Space Complexity: O(m*n)
16
+ vector<vector<int >> updateMatrixBFS (vector<vector<int >>& mat) {
17
+ vector<int > ADJACENT = {0 , 1 , 0 , -1 , 0 };
18
+ queue<pair<int , int >> next;
19
+
20
+ for (int row = 0 ; row < mat.size (); row++){
21
+ for (int col = 0 ; col < mat[row].size (); col++){
22
+ if (mat[row][col] == 0 ) {
23
+ next.push ({row, col});
24
+ }
25
+ else {
26
+ mat[row][col] = -1 ;
27
+ }
28
+ }
29
+ }
30
+ while (!next.empty ()) {
31
+ auto [row, col] = next.front ();
32
+ next.pop ();
33
+
34
+ for (int i = 0 ; i < 4 ; i++){
35
+ int newRow = row + ADJACENT[i], newCol = col + ADJACENT[i+1 ];
36
+ if (newRow < 0 || newRow >= mat.size () || newCol < 0 || newCol >= mat[0 ].size () || mat[newRow][newCol] != -1 ){
37
+ continue ;
38
+ }
39
+ mat[newRow][newCol] = mat[row][col] + 1 ;
40
+ next.push ({newRow, newCol});
41
+ }
42
+ }
43
+ return mat;
44
+ }
45
+
46
+ // Dynamic Programming (restrict checks)
47
+ // Time Complexity: O(m*n)
48
+ // Space Complexity: O(1)
49
+ vector<vector<int >> updateMatrix (vector<vector<int >>& mat) {
50
+ int rows = mat.size (), cols = mat[0 ].size ();
51
+ int maxDistance = rows + cols; // longest possible path (diameter)
52
+
53
+ for (int r = 0 ; r < rows; r++){
54
+ for (int c = 0 ; c < cols; c++){
55
+ if (mat[r][c] == 0 ) { continue ; }
56
+ int top = maxDistance, right = maxDistance;
57
+ if (r - 1 >= 0 ) { top = mat[r-1 ][c]; }
58
+ if (c - 1 >= 0 ) { right = mat[r][c-1 ]; }
59
+ mat[r][c] = min (top, right) + 1 ;
60
+ }
61
+ }
62
+ for (int r = rows - 1 ; r >= 0 ; r--){
63
+ for (int c = cols - 1 ; c >= 0 ; c--){
64
+ if (mat[r][c] == 0 ) { continue ; }
65
+ int down = maxDistance, left = maxDistance;
66
+ if (r + 1 < rows) { down = mat[r+1 ][c]; }
67
+ if (c + 1 < cols) { left = mat[r][c+1 ]; }
68
+ mat[r][c] = min (mat[r][c], min (down, left) + 1 );
69
+ }
70
+ }
71
+ return mat;
72
+ }
0 commit comments