关闭

LeetCode37.Sudoku solver电脑来解数独

标签: Leetcode数独
290人阅读 评论(0) 收藏 举报
分类:


#include <vector>
#include <iostream>
#include "cocos2d.h"
using namespace std;
using namespace cocos2d;


void printvector(vector<vector<char>>& board)
{
log("----------------------------------");
for (int i = 0; i < board.size(); i++) {
string s;
for (int j = 0; j < board[i].size(); j++) {
s.append(" ");
s.append(string(1, board[i][j]));
}
log(s.c_str());
}
}


struct Vex{
int row;
int col;
int val;
Vex(int r, int c, int v) : row(r), col(c), val(v){}
};


class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
vector<Vex> vi;
int i = 0;
for (; i < board.size(); i++) {
int j = 0;
for (; j < board[i].size(); j++) {
if (board[i][j] == '.') {
int v = 1;
while (true) {
for (; v <= 9; v++) {
if (isOk(board, i, j, v + '0')) {
break;
}
}
if (v == 10) {
//printvector(board);
v = vi.back().val+1;
i = vi.back().row;
j = vi.back().col;
board[i][j] = '.';
vi.pop_back();
}
else {
vi.push_back(Vex(i, j, v));
board[i][j] = '0' + v;
break;
}
}
}
}
}
}
bool isOk(vector<vector<char>>& board, int row, int col, char val)
{
for (int c = 0; c < 9; c++) {
if (board[row][c] == val) {
return false;
}
if (board[c][col] == val) {
return false;
}
if (board[(row / 3)*3 + c / 3][(col / 3)*3 + c % 3] == val) {
return false;
}
}
return true;
}
};




void sudoku_test()
{

vector<string> sv{ "..9748...", "7........", ".2.1.9...", "..7...24.", ".64.1.59.", ".98...3..", "...8.3.2.", "........6", "...2759.." };
vector<vector<char>> vvc;
for (int i = 0; i < sv.size(); i++) {
vvc.push_back(vector<char>(sv[i].begin(), sv[i].end()));
}
Solution s;
printvector(vvc);
s.solveSudoku(vvc);
printvector(vvc);


}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人简介
    个人资料
    • 访问:760126次
    • 积分:7977
    • 等级:
    • 排名:第2700名
    • 原创:274篇
    • 转载:6篇
    • 译文:1篇
    • 评论:204条
    我的小站
    最新评论
    --
    我要啦免费统计