Advertisement
Guest User

Untitled

a guest
May 25th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.03 KB | None | 0 0
  1. /**
  2.  * 2D matrix, with obstacles (-1), empty cell(0), and packages(positive #)
  3.  * and a set of packages(integer id).
  4.  * Starting from (0,0), find the path to pick up all packages.
  5.  */
  6. public class FindPathForPackages {
  7.     private static class Point{
  8.         int x, y;
  9.  
  10.         public Point(int x, int y) {
  11.             this.x = x;
  12.             this.y = y;
  13.         }
  14.  
  15.         @Override
  16.         public String toString() {
  17.             return "{" + x + ", " + y + '}';
  18.         }
  19.     }
  20.  
  21.     List<List<Point>> paths = new ArrayList<>();
  22.  
  23.     List<List<Point>> findPath(int[][] M, Set<Integer> pkgs) {
  24.         int row = M.length;
  25.         int col = M[0].length;
  26.         boolean[][] V = new boolean[row][col];
  27.  
  28.         helper(M, 0, 0, pkgs, V, new ArrayList<>());
  29.  
  30.         return paths;
  31.     }
  32.  
  33.     private void helper(int[][] M, int x, int y, Set<Integer> pkgs, boolean[][] V, List<Point> cur) {
  34.         if (pkgs.contains(M[x][y])) {
  35.             pkgs.remove(M[x][y]);
  36.             if (pkgs.isEmpty()) {
  37.                 paths.add(new ArrayList<>(cur));
  38.                 return;
  39.             }
  40.         }
  41.         V[x][y] = true;
  42.         int[] dx = {0, 0, 1, -1};
  43.         int[] dy = {1, -1, 0, 0};
  44.  
  45.         for(int k = 0; k < 4; k++) {
  46.             int xx = dx[k] + x;
  47.             int yy = dy[k] + y;
  48.  
  49.             if(isValid(M, xx, yy, V)) {
  50.                 V[xx][yy] = true;
  51.                 cur.add(new Point(xx, yy));
  52.                 helper(M, xx, yy, pkgs, V,cur);
  53.                 cur.remove(cur.size() - 1);
  54.                 V[xx][yy] = false;
  55.             }
  56.         }
  57.     }
  58.  
  59.     private boolean isValid(int[][] m, int x, int y, boolean[][] v) {
  60.         return (x >= 0 && y >= 0 && x < m.length && y < m[0].length && m[x][y] != -1 && !v[x][y]);
  61.     }
  62.  
  63.     public static void main(String args[]) {
  64.         int[][] M = {{0, 0, -1, 0}, {0, 3, 0, 7}, {0, -1, 0, 8}};
  65.  
  66.         Set<Integer> pkgs = new HashSet<>();
  67.         pkgs.add(3);
  68.         pkgs.add(7);
  69.         pkgs.add(8);
  70.  
  71.         List<List<Point>> result = new FindPathForPackages().findPath(M, pkgs);
  72.  
  73.         System.out.println(result);
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement