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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| class Solution { int[] dx = {-1, 1, 0, 0}; int[] dy = {0, 0, -1, 1}; List<int[]> ans; Set<String> mem; boolean[][] global; int[] p;
public int[][] bicycleYard(int[] position, int[][] terrain, int[][] obstacle) { ans = new ArrayList<>(); mem = new HashSet<>(); global = new boolean[terrain.length][terrain[0].length]; p = position; bfs(1, position[0], position[1], terrain, obstacle); int[][] res = new int[ans.size()][2]; for (int i = 0; i < ans.size(); i++) { res[i] = ans.get(i); } Arrays.sort(res, (o1, o2) -> { if (o1[0] == o2[0]) { return Integer.compare(o1[1], o2[1]); } else { return Integer.compare(o1[0], o2[0]); } }); return res; }
public void bfs(int curr, int x, int y, int[][] terrain, int[][] obstacle) { if (x >= 0 && y >= 0 && x < terrain.length && y < terrain[0].length) { for (int i = 0; i < 4; i++) { int newX = x + dx[i]; int newY = y + dy[i]; if (newX >= 0 && newY >= 0 && newX < terrain.length && newY < terrain[0].length) { int next = curr + terrain[x][y] - terrain[newX][newY] - obstacle[newX][newY]; String k = newX + "-" + newY + "-" + next; if (mem.contains(k)) { continue; } mem.add(k); if (next >= 1) { if (next == 1 && (newX != p[0] || newY != p[1]) && !global[newX][newY]) { global[newX][newY] = true; ans.add(new int[]{newX, newY}); } bfs(next, newX, newY, terrain, obstacle); } } } } } }
|