[InterviewBit] Kth Manhattan Distance Neighbourhood

Kth Manhattan Distance Neighbourhood

  • 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
vector<vector<int> > Solution::solve(int A, vector<vector<int>> &B) {
int n = B.size(), m = B[0].size();
vector<vector<int>> res = B;
queue<array<int,5>> q;
for(int i = 0; i < B.size(); i++) {
for(int j = 0; j < B[0].size(); j++) {
q.push({B[i][j], i, j, i, j});
}
}
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
while(q.size()) {
auto [v,y,x,oy,ox] = 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 res[ny][nx] < v and abs(ny-oy) + abs(nx - ox) <= A) {
res[ny][nx] = v;
q.push({v,ny,nx,oy,ox});
}
}
}

return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/24/PS/interviewbit/kth-manhattan-distance-neighbourhood/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.