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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| class Solution { private static final Map<Character, int[][]> PIECE_DIRS = Map.of( 'r', new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}, 'b', new int[][]{{1, 1}, {-1, 1}, {-1, -1}, {1, -1}}, 'q', new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}} );
public int countCombinations(String[] pieces, int[][] positions) { int n = pieces.length; Move[][] allMoves = new Move[n][]; for (int i = 0; i < n; i++) { allMoves[i] = generateMoves(positions[i][0], positions[i][1], PIECE_DIRS.get(pieces[i].charAt(0))); }
Move[] path = new Move[n]; return dfs(0, n, allMoves, path); }
private record Move(int x0, int y0, int dx, int dy, int step) { }
private Move[] generateMoves(int x0, int y0, int[][] dirs) { final int SIZE = 8; List<Move> moves = new ArrayList<>(); moves.add(new Move(x0, y0, 0, 0, 0)); for (int[] d : dirs) int x = x0 + d[0], y = y0 + d[1]; for (int step = 1; 0 < x && x <= SIZE && 0 < y && y <= SIZE; step++) { moves.add(new Move(x0, y0, d[0], d[1], step)); x += d[0]; y += d[1]; } } return moves.toArray(Move[]::new); }
private boolean isValid(Move m1, Move m2) { int x1 = m1.x0, y1 = m1.y0; int x2 = m2.x0, y2 = m2.y0; for (int i = 0; i < Math.max(m1.step, m2.step); i++) { if (i < m1.step) { x1 += m1.dx; y1 += m1.dy; } if (i < m2.step) { x2 += m2.dx; y2 += m2.dy; } if (x1 == x2 && y1 == y2) { return false; } } return true; }
private int dfs(int i, int n, Move[][] allMoves, Move[] path) { if (i == n) { return 1; } int res = 0; outer: for (Move move1 : allMoves[i]) { for (int j = 0; j < i; j++) { if (!isValid(move1, path[j])) { continue outer; } } path[i] = move1; res += dfs(i + 1, n, allMoves, path); } return res; } }
|