Advertisement
jorupp

https://leetcode.com/problems/matrix-cells-in-distance-order

Jun 16th, 2023
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. function allCellsDistOrder(rows: number, cols: number, rCenter: number, cCenter: number): number[][] {
  2. const getKey = ([x, y]: [number, number]) => `${x}_${y}`;
  3. const inRange = ([x, y]: [number, number]) => x < rows && y < cols && x >= 0 && y >= 0;
  4. const getNeighbors = ([x, y]: [number, number]): [number, number][] => ([ [x+1, y], [x-1, y], [x, y+1], [x, y-1] ]);
  5.  
  6. // add at the end, iterate from the front, which means we'll end up in order
  7. const all: [number, number][] = [ [rCenter, cCenter ] ];
  8. const seen = new Set<string>([getKey(all[0])]);
  9. for(let i=0; i<all.length; i++) {
  10. for(const n of getNeighbors(all[i])) {
  11. if (!inRange(n)) continue;
  12. const key = getKey(n);
  13. if (seen.has(key)) continue;
  14. seen.add(key);
  15. all.push(n);
  16. }
  17. }
  18.  
  19. return all;
  20. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement