Advertisement
SalmaYasser

Untitled

Oct 26th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. // https://leetcode.com/discuss/interview-question/356150
  2. public class Main {
  3. private static final int[][] DIRS = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
  4.  
  5. public static int minDist(char[][] grid) {
  6. Queue<Point> q = collectSources(grid);
  7. for (int dist = 0; !q.isEmpty(); dist++) {
  8. for (int sz = q.size(); sz > 0; sz--) {
  9. Point p = q.poll();
  10.  
  11. if (grid[p.r][p.c] == 'X') return dist;
  12. grid[p.r][p.c] = 'D'; // mark as visited
  13.  
  14. for (int[] dir : DIRS) {
  15. int r = p.r + dir[0];
  16. int c = p.c + dir[1];
  17. if (isSafe(grid, r, c)) {
  18. q.add(new Point(r, c));
  19. }
  20. }
  21.  
  22. }
  23. }
  24. return -1;
  25. }
  26.  
  27. private static Queue<Point> collectSources(char[][] grid) {
  28. Queue<Point> sources = new ArrayDeque<>();
  29. for (int r = 0; r < grid.length; r++) {
  30. for (int c = 0; c < grid[0].length; c++) {
  31. if (grid[r][c] == 'S') {
  32. sources.add(new Point(r, c));
  33. }
  34. }
  35. }
  36. return sources;
  37. }
  38.  
  39. private static boolean isSafe(char[][] grid, int r, int c) {
  40. return r >= 0 && r < grid.length && c >= 0 && c < grid[0].length && grid[r][c] != 'D';
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement