最近,我遇到了这个问题,因为时间的推移我无法解决它。如何使用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 –