• 随笔


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

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

  • 相关阅读:
    android焦点
    URI和URL的区别比较与理解
    Android Bundle类
    repo命令
    ubuntu adb找不到设备
    【python】-网络编程
    【python】-反射
    【python】-类的特殊成员方法
    【python】-7-面向对象的进阶
    【python】-多态
  • 原文地址:https://www.cnblogs.com/steamedbun/p/5859909.html
Copyright © 2020-2023  润新知