Recently, I encountered this problem and I can't solve it because of time over.
'Make a program that answers how many ways to paint r by r field with n different colors, without using the same color at same row, same column.'
I coded for it, but it takes over 30 mins to answer at only 6 by 6 field with 6 colors.
So, I thought about multi-dimensional memoization, but I don't have an idea to add memoization array at my code.
Please help me make my code faster or suggest the new way.
#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);
}