Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bits/stdc++.h"
- using namespace std;
- const int N = 12;
- int dp[N][N], maskCol[N], maskRow[N];
- int refMask[N][N], matMask[N];
- int cnt = 0;
- bool check() {
- for (int i = 1; i <= 9; i += 3) {
- for (int j = 1; j <= 9; j += 3) {
- int maskCol = 0;
- for (int r = i; r < i + 3; ++r) {
- for (int c = j; c < j + 3; ++c) {
- if (!dp[r][c]) return 0;
- if (maskCol & (1<<dp[r][c])) return 0;
- maskCol |= (1<<dp[r][c]);
- }
- }
- }
- }
- for (int i = 1; i <= 9; ++i) {
- int maskCol = 0;
- for (int j = 1; j <= 9; ++j) {
- if (maskCol & (1<<dp[i][j])) return 0;
- maskCol |= (1<<dp[i][j]);
- }
- }
- for (int i = 1; i <= 9; ++i) {
- int maskCol = 0;
- for (int j = 1; j <= 9; ++j) {
- if (maskCol & (1<<dp[j][i])) return 0;
- maskCol |= (1<<dp[j][i]);
- }
- }
- // Uncomment to print solution
- // for (int i = 1; i <= 9; i += 1) {
- // for (int j = 1; j <= 9; j += 1) {
- // cout << dp[i][j] << " \n"[j==9];
- // }
- // }
- // exit(0);
- return true;
- }
- int ans = 0;
- void go(int row, int col) {
- ++cnt;
- if (row == 1 and col == 10 && check()) {
- return;
- }
- if (cnt > 5e5) {
- cout << "Seems like infinite loop\n";
- exit(0);
- }
- if (row > 9 or col > 9) return;
- if (dp[row][col]) {
- if (row == 9) go(1,col+1);
- else go(row+1,col);
- }
- else {
- for (int i = 1; i <= 9; ++i) {
- if (!(maskCol[col] & (1<<i)) && !(maskRow[row] & (1<<i))) {
- if (matMask[refMask[row][col]] & (1<<i)) continue;
- maskCol[col] += (1<<i);
- maskRow[row] += (1<<i);
- matMask[refMask[row][col]] += 1<<i;
- dp[row][col] = i;
- if (row == 9) go(1,col+1);
- else go(row+1,col);
- maskCol[col] -= (1<<i);
- maskRow[row] -= (1<<i);
- matMask[refMask[row][col]] -= 1<<i;
- dp[row][col] = 0;
- }
- }
- }
- }
- int main() {
- int ok = 1;
- for (int i = 1; i <= 9; i += 3) {
- for (int j = 1; j <= 9; j += 3) {
- for (int r = i; r < i + 3; ++r) {
- for (int c = j; c < j + 3; ++c) {
- refMask[r][c] = ok;
- }
- }
- ++ok;
- }
- }
- // go(1,1);
- return 0;
- }
Add Comment
Please, Sign In to add comment