[InterviewBit] Valid Path

Valid Path

  • Time :
  • Space :
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
string Solution::solve(int A, int B, int C, int D, vector<int> &E, vector<int> &F) {
vector<vector<int>> vis(B+1,vector<int>(A+1));
for(int i = 0; i <= B; i++) {
for(int j = 0; j <= A; j++) {
for(int k = 0; k < C and !vis[i][j]; k++) {
if(sqrt(pow(E[k]-j, 2) + pow(F[k]-i, 2)) <= D) vis[i][j] = 1;
}
}
}
if(vis[0][0] or vis[B][A]) return "NO";
queue<pair<int, int>> q;
q.push({0,0});
int dy[8] {-1,-1,-1,0,1,1,1,0}, dx[8]{-1,0,1,1,1,0,-1,-1};
while(q.size()) {
auto [y,x] = q.front(); q.pop();
for(int i = 0; i < 8; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny <= B and 0 <= nx and nx <= A and !vis[ny][nx]) {
vis[ny][nx] = 1;
q.push({ny,nx});
}
}
}
return vis[B][A] ? "YES" : "NO";
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/24/PS/interviewbit/valid-path/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.