-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path542. 01 Matrix.cpp
More file actions
97 lines (59 loc) · 1.74 KB
/
Copy path542. 01 Matrix.cpp
File metadata and controls
97 lines (59 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Solution
{
public:
vector < vector <int> > updateMatrix(vector<vector<int>>& matrix)
{
int m = matrix.size();
if (m < 1) return matrix;
int n = matrix[0].size();
if (n < 1) return matrix;
int row = matrix.size();
int col = matrix[0].size();
for(int i = 0 ; i < matrix.size(); i++)
{
for(int j = 0 ; j < matrix[i].size() ; j++)
{
bfs(i,j,matrix,row,col);
// cout<< matrix[i][j];
}
// cout<<endl;
}
return matrix;
}
private:
int dx[4] = {0, 0, +1, -1};
int dy[4] = {+1, -1, 0, 0};
// int dist[1000][1000];
void bfs(int start_row, int start_col, vector<vector<int>>&matrix, int r, int c)
{
queue< data > q;
int dist = 0;
q.push({{start_row, start_col, dist}});
while ( ! q.empty() )
{
data curr = q.front();
q.pop();
int row = curr.arr[0];
int col = curr.arr[1];
int dist = curr.arr[2];
if (matrix[row][col] == 0)
{
matrix[start_row][start_col] = dist;
return;
}
for (auto i = 0; i < 4; ++i)
{
int new_row = row + dx[i];
int new_col = col + dy[i];
if (new_row >=0 and new_row < r and new_col >=0 and new_col < c)
{
q.push({new_row, new_col, dist+1 });
}
}
}
}
struct data
{
int arr[100];
} ;
};