[InterviewBit] Path in Matrix

Path in Matrix

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int Solution::checkPath(vector<vector<int> > &A) {
queue<pair<int, int>> q;
int n = A.size(), m = A[0].size();
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
if(A[i][j] == 1) q.push({i,j});
}
while(q.size()) {
auto [y,x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and A[ny][nx]) {
if(A[ny][nx] == 2) return 1;
A[ny][nx] = 0;
q.push({ny,nx});
}
}
}
return false;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/17/PS/interviewbit/path-in-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.