Sudoku Solver
来源:互联网 发布:电脑锣编程代码 编辑:程序博客网 时间:2024/06/06 08:39
每日算法——leetcode系列
问题 Sudoku Solver
Difficulty: Hard
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character
'.'
.You may assume that there will be only one unique solution.
A sudoku puzzle…
…and its solution numbers marked in red.
class Solution {public: void solveSudoku(vector<vector<char>>& board) { }};
翻译
数独解决器
难度系数:困难
写一个程序来实现通过填充空格求解数独。
空格用'.'
表示。
你可以假定只有唯一解。
思路
题目的意思应该是给一个未完成的数独,然后通过程序可以自动填充来求解数独。
- 先查看现有的数字用Valid Sudoku检查符合数独的条件不
- 递归
从board的第一格开遍历,- 如果当前符号不为
.
,则遍历该行中下一格(先行后列),如果遍历到的格数大于了最大列数,则遍历行,终止条件行数也大于最大行数 - 为’.’时,从1-9,依次先一个插入,再重复整个过程
- 如果当前符号不为
代码
class Solution {public: void solveSudoku(vector<vector<char>>& board) { if (isValidSudoku(board) == false){ return; } recursiveSudoKu(board, 0, 0); }private: bool isValidSudoku(vector<vector<char> > &board) { for (int i = 0; i < 9; ++i){ for (int j = 0; j < 9; ++j){ rowMap[i][j] = {false}; colMap[i][j] = {false}; smallBoardMap[i][j] = {false}; } } for(int i = 0; i < board.size(); ++i){ for (int j = 0; j < board[i].size(); ++j){ if (board[i][j] == '.'){ continue; } int idx = board[i][j] - '0' - 1; // 行 if (rowMap[i][idx] == true){ return false; } rowMap[i][idx] = true; // 列 if (colMap[j][idx] == true) { return false; } colMap[j][idx] = true; // 小区域 int area = (i/3) * 3 + (j/3); if (smallBoardMap[area][idx] == true) { return false; } smallBoardMap[area][idx] = true; } } return true; } bool recursiveSudoKu(vector<vector<char>> &board, int row, int col){ if (row >= 9) { return true; } if (col >= 9){ return recursiveSudoKu(board, row+1, 0); } if (board[row][col] != '.'){ return recursiveSudoKu(board, row, col+1); } int area; for(int i=0; i < 9; ++i){ area = (row/3) * 3 + (col/3); if (rowMap[row][i] || colMap[col][i] || smallBoardMap[area][i]){ continue; } board[row][col] = i + '1'; rowMap[row][i] = colMap[col][i] = smallBoardMap[area][i] = true; if (recursiveSudoKu(board, row, col+1)){ return true; } board[row][col] = '.'; rowMap[row][i] = colMap[col][i] = smallBoardMap[area][i] = false; } return false; } bool rowMap[9][9]; bool colMap[9][9]; bool smallBoardMap[9][9];};
0 0
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- Sudoku Solver
- PorterDuffXferMode不正确的真正原因PorterDuffXferMode深入试验)
- oracle----------数据类型,增删改
- 1.XML 简介
- poj 1979 Red and Black
- Quartz 2D
- Sudoku Solver
- 数字字符串四则运算
- Android 动画学习
- sdl显示bmp
- gdb调试正在运行进程
- Android进阶——git上传代码到coding.net
- 拓胜培训Java,每天的点点滴滴
- H5页面设计
- Applied Natural Language Processing —— 读书笔记 第二章