随笔 - 数独游戏

无聊的时候随手写了一个解数独的程序= =,记录一下

 

#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
using namespace std;

#define Int __int64
#define INF 0x3f3f3f3f

int maze[15][15];
bool row[15][15];
bool column[15][15];
bool cube[15][15][15];
bool judge;
int ans, res;

bool JudgeRow(int x, int y, int n) {
  if (row[x][n]) return false;
  else return true;
}

bool JudgeColumn(int x, int y, int n) {
  if (column[y][n]) return false;
  else return true;
}

bool JudgeCube(int x, int y, int n) {
  int i = x / 3;
  int j = y / 3;
  if (cube[i][j][n]) return false;
  else return true;
}

void Solve(int x, int y, int ans) {
  if (judge) return ;
  if (ans == res) {
    for (int i = 0; i < 9; i++) {
      for (int j = 0; j < 9; j++) {
        cout << maze[i][j] << " ";
      }
      cout << endl;
    }
    judge = true;
    return ;
  }
  if (maze[x][y] > 0) {
    int xx = x;
    int yy = y + 1;
    if (yy >= 9) {
    yy = 0;
    xx += 1;
  }
  Solve(xx, yy, ans);
  } else {
    for (int i = 1; i <= 9; i++) {
      if (JudgeRow(x, y, i) && JudgeCube(x, y, i) && JudgeColumn(x, y, i)) {
        maze[x][y] = i;
        row[x][i] = true;
        column[y][i] = true;
        cube[x / 3][y / 3][i] = true;

        Solve(x, y, ans + 1);

        maze[x][y] = 0;
        row[x][i] = false;
        column[y][i] = false;
        cube[x / 3][y / 3][i] = false;
      }
    }
  }
}

int main() {
  //freopen("input.txt", "r", stdin);
  memset(maze, 0, sizeof(maze));
  memset(row, false, sizeof(row));
  memset(column, false, sizeof(column));
  memset(cube, false, sizeof(cube));
  //初始化题目信息
  res = ans = 0;
  for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
      cin >> maze[i][j];
      if (maze[i][j] > 0) {
        res++;
        row[i][maze[i][j]] = true;
        column[j][maze[i][j]] = true;
        cube[i / 3][j / 3][maze[i][j]] = true;
      }
    }
  }
  res = 81 - res;
  //开始填空
  judge = false;
  Solve(0, 0, 0);
  if (!judge) cout << "No Answer!" << endl;
}

转载于:https://www.cnblogs.com/steamedbun/p/5859909.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值