码迷,mamicode.com
首页 > 其他好文 > 详细

随笔 - 数独游戏

时间:2016-09-10 19:05:17      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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

 

#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;
}

随笔 - 数独游戏

标签:

原文地址:http://www.cnblogs.com/steamedbun/p/5859909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!