Untitled
unknown
plain_text
2 years ago
1.5 kB
8
Indexable
import java.util.Scanner;
public class ColorCombinationBacktracking {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 1; t <= T; t++) {
int n = sc.nextInt();
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}
int count = 0;
int[] color = new int[n * n];
backtrack(matrix, color, 0);
System.out.println("Case #" + t);
System.out.println(count);
}
}
private static void backtrack(int[][] matrix, int[] color, int i) {
if (i == matrix.length * matrix.length) {
count++;
return;
}
for (int c = 0; c < 4; c++) {
if (isSafe(matrix, color, i, c)) {
color[i] = c;
backtrack(matrix, color, i + 1);
}
}
}
private static boolean isSafe(int[][] matrix, int[] color, int i, int c) {
int row = i / matrix.length;
int col = i % matrix.length;
for (int j = 0; j < matrix.length; j++) {
if (matrix[row][j] == 1 && color[j * matrix.length + c] == c) {
return false;
}
if (matrix[j][col] == 1 && color[i + j * matrix.length] == c) {
return false;
}
}
return true;
}
}
Editor is loading...