Untitled
unknown
plain_text
a year ago
3.3 kB
2
Indexable
Never
import java.util.Scanner; public class StoneGame { private static final char WHITE = 'w'; private static final char BLACK = 'b'; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCaseCount = scanner.nextInt(); for (int testCaseNumber = 1; testCaseNumber <= testCaseCount; testCaseNumber++) { char[][] board = new char[4][4]; for (int row = 0; row < 4; row++) { String line = scanner.next(); for (int col = 0; col < 4; col++) { board[row][col] = line.charAt(col); } } int minimumOperationCount = Integer.MAX_VALUE; backtrack(board, 0, 0, 0, 0, minimumOperationCount); if (minimumOperationCount == Integer.MAX_VALUE) { System.out.println("Case #" + testCaseNumber + " impossible"); } else { System.out.println("Case #" + testCaseNumber + " " + minimumOperationCount); } } scanner.close(); } private static void backtrack(char[][] board, int row, int col, int whiteCount, int blackCount, int minimumOperationCount) { if (row == 4) { if (whiteCount == 0 || blackCount == 0) { minimumOperationCount = Math.min(minimumOperationCount, Math.max(whiteCount, blackCount)); } return; } if (minimumOperationCount <= Math.max(whiteCount, blackCount)) { return; } for (int rowOffset = -1; rowOffset <= 1; rowOffset++) { for (int colOffset = -1; colOffset <= 1; colOffset++) { if (rowOffset == 0 && colOffset == 0) { continue; } int newRow = row + rowOffset; int newCol = col + colOffset; if (isValidCell(board, newRow, newCol)) { int currentOperationCount = 1 + Math.max(whiteCount, blackCount); board[row][col] = board[row][col] == WHITE ? BLACK : WHITE; board[newRow][newCol] = board[newRow][newCol] == WHITE ? BLACK : WHITE; board[row + rowOffset][col + colOffset] = board[row + rowOffset][col + colOffset] == WHITE ? BLACK : WHITE; board[row + rowOffset][col] = board[row + rowOffset][col] == WHITE ? BLACK : WHITE; board[row][col + colOffset] = board[row][col + colOffset] == WHITE ? BLACK : WHITE; backtrack(board, newRow, newCol, whiteCount + 1, blackCount - 1, minimumOperationCount); board[row][col] = board[row][col] == BLACK ? WHITE : BLACK; board[newRow][newCol] = board[newRow][newCol] == BLACK ? WHITE : BLACK; board[row + rowOffset][col + colOffset] = board[row + rowOffset][col + colOffset] == BLACK ? WHITE : BLACK; board[row + rowOffset][col] = board[row + rowOffset][col] == BLACK ? WHITE : BLACK; board[row][col + colOffset] = board[row][col + colOffset] == BLACK ? WHITE : BLACK; } } } } private static boolean isValidCell(char[][] board, int row, int col) { return 0 <= row && row < 4 && 0 <= col && col < 4; } }