zoukankan      html  css  js  c++  java
  • 随笔

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

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

  • 相关阅读:
    (基本知识)Redis 字符串(String)相关函数
    (基本知识)Redis 键相关命令函数
    (基本知识)Redis连接与安全
    centos7 php开发环境安装-Redis
    centos7 php开发环境安装--配置SSL(Apache为例)
    centos7 php开发环境安装-Git
    centos7 php开发环境安装-Nginx
    串口发送数据
    七大查找算法
    基于STM32原子战舰板内存管理源码详解
  • 原文地址:https://www.cnblogs.com/steamedbun/p/5859909.html
Copyright © 2011-2022 走看看