37Sudoku Solver

来源:互联网 发布:java单例模式的作用 编辑:程序博客网 时间:2024/06/05 07:50

37 Sudoku Solver

链接:https://leetcode.com/problems/sudoku-solver/
问题描述:
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.

Hide Tags Backtracking Hash Table

解数独,原理就是暴力破解,不断地填数字知道找到一个解。这里需要用到http://blog.csdn.net/efergrehbtrj/article/details/46804961 这一题的验证。

class Solution {public:    bool mSolveSudoku(vector<vector<char> > &board)    {        for (int i = 0; i < 9;i++)         {            for (int j = 0; j < 9; j++)             {                if ('.' == board[i][j])                 {                    for (int k = 1; k <= 9; k++)                     {                       board[i][j] = '0' + k;                         if (isValidSudoku(board))                         {                             if (mSolveSudoku(board))                              {                                return true;                             }                       }                        board[i][j] = '.';                    }                   return false;                }            }         }        return true;    }    void solveSudoku(vector<vector<char>>& board)     {        mSolveSudoku(board);    }    bool isValidSudoku(vector<vector<char>>& board)     {       char table1[9][9],table2[9][9],table3[9][9];       memset(table1,0,81*sizeof(char));       memset(table2,0,81*sizeof(char));       memset(table3,0,81*sizeof(char));        for(int i=0;i<9;i++)        {          for(int j=0;j<9;j++)          {              if(board[i][j]>='1'&&board[i][j]<='9')              {               if( table1[i/3*3+j/3][board[i][j]-'1']==1 ||                   table2[i][board[i][j]-'1']==1 ||                   table3[j][board[i][j]-'1']==1)                   return false;               table1[i/3*3+j/3][board[i][j]-'1']=1;               table2[i][board[i][j]-'1']=1;               table3[j][board[i][j]-'1']=1;              }          }        }        return true;    }};
0 0
原创粉丝点击