最近,我遇到了這個問題,因爲時間的推移我無法解決它。如何使用n種不同的顏色在同一列上使用相同的顏色繪製r x r字段
'製作一個程序,可以通過r字段使用n種不同的顏色來繪製r的方式,而不會在同一行,同一列使用相同的顏色。
我編碼爲它,但它需要超過30分鐘回答6只6乘6色的領域。
所以,我想到了多維memoization,但我沒有想法在我的代碼中添加memoization數組。
請幫我讓我的代碼更快或建議新的方式。
#include<stdio.h>
#include<stdlib.h>
int check[100][100], scheck[100][100], n, r;
long long cnt;
void arr(int x, int y) {
int i, k=0;
for (int j = 0; j < n; j++) { //about n colors
if (check[y][j] == 0 && scheck[x][j] == 0) { //if there is no j th color in same row and column
check[y][j] = 1; // check 'there is j th color in y th row, x th column
scheck[x][j] = 1; // to make same effect with inputing j at virtual field[y][x]
if (x == r - 1) { // if x th column is the end of right
if (y == r - 1) cnt++; // if y th column is the bottom, count this
else arr(0, y + 1); // else fill next row, first column
}
else arr(x + 1, y); // else fill next right square
check[y][j] = 0; // check 'there is no j th color in y th row, x th column
scheck[x][j] = 0; // to make same effect with erasing j virtual field[y][x]
}
}
return;
}
void main() {
printf("Input n, r (paint r x r field with n colors, same color cannot be used in same column and row) \n: ");
scanf("%d %d", &n, &r);
arr(0, 0);
printf("There are %ld ways to paint.\n", cnt);
}
您的問題名稱是拉丁廣場希望它會有所幫助。檢查這裏例如:https://math.stackexchange.com/questions/145228/formula-for-the-number-of-latin-squares-of-size-n –