/* * Solution to Su-Su-Sudoku */ import java.util.*; public class Sudoku { public static int n; // number of test cases public static int[][] board; // sudoku board public static int rhole[], chole[]; // locations of five empty spots public static ArrayList possible[]; public static Scanner in; public static void main(String[] args) { in = new Scanner(System.in); n = in.nextInt(); for (int i = 0; i < n; i++) { if (i > 0) System.out.println(); board = new int[9][9]; rhole = new int[5]; chole = new int[5]; int holecount = 0; for (int row = 0; row < 9; row++) { String line = in.next(); for (int col = 0; col < 9; col++) { board[row][col] = Integer.parseInt(""+line.charAt(col)); if (board[row][col] == 0) { rhole[holecount] = row; chole[holecount] = col; holecount++; } } } if (solve()) printBoard(); else System.out.println("Could not complete this grid."); } } public static boolean solve() { possible = new ArrayList[5]; for (int i = 0; i < 5; i++) possible[i] = new ArrayList(); for (int i = 0; i < 5; i++) { int r = rhole[i]; int c = chole[i]; for (int j = 1; j <= 9; j++) { boolean okay = true; if (rowHas(r,j)) { okay = false; } if (colHas(c,j)) { okay = false; } if (blockHas(r/3,c/3,j)) { okay = false; } if (okay) possible[i].add(j); } } for (int i0: possible[0]) { board[rhole[0]][chole[0]] = i0; for (int i1: possible[1]) { board[rhole[1]][chole[1]] = i1; for (int i2: possible[2]) { board[rhole[2]][chole[2]] = i2; for (int i3: possible[3]) { board[rhole[3]][chole[3]] = i3; for (int i4: possible[4]) { board[rhole[4]][chole[4]] = i4; if (valid()) return true; } } } } } return false; } public static boolean valid() { for (int i = 0; i < 9; i++) { for (int j = 1; j <= 9; j++) { boolean rfound = false,cfound=false; for (int k = 0; k < 9; k++) { if (board[i][k] == j) rfound = true; if (board[k][i] == j) cfound = true; } if (!(rfound && cfound)) return false; } } for (int i = 0; i< 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 1; k <= 9; k++) { boolean blockfound = false; for (int r = 0; r < 3; r++) { for (int c = 0; c < 3; c++) { if (board[3*i+r][3*j+c] == k) blockfound = true; } } if (!blockfound) return false; } } } return true; } public static boolean rowHas(int r, int j) { for (int i = 0; i < 9; i++) if (board[r][i] == j) return true; return false; } public static boolean colHas(int c, int j) { for (int i = 0; i < 9; i++) if (board[i][c] == j) return true; return false; } public static boolean blockHas(int r, int c, int j) { for (int i = 0; i < 3; i++) { for (int k = 0; k < 3; k++) { if (board[r*3+i][c*3+k] == j) return true; } } return false; } public static void printBoard() { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) System.out.print(board[row][col]); System.out.println(); } } }