Leetcode -- Sudoku Solver

Source: Internet
Author: User

Ideas:

DFS + Sudoku game rules.

The rule of the sudoku game is:

Duplicate numbers are not allowed in the same column of the same row, and duplicate numbers are not allowed in every 9 intrauterine devices.

 1 class Solution { 2 public: 3     bool isValid(vector<vector<char> > &board, int a, int b) { 4         int i,j; 5         for(i = 0; i < 9; i++) 6             if(i != a && board[i][b] == board[a][b]) 7                 return false; 8  9         for(j = 0; j < 9; j++)10             if(j != b && board[a][j] == board[a][b])11                 return false;12 13         int x = a/3*3;14         int y = b/3*3;15         for(i = 0; i < 3; i++)16             for(j = 0; j< 3; j++)17                 if(x+i != a && y+j != b && board[x+i][y+j] == board[a][b])18                     return false;19         return true;20     }21     bool solveSudokudfs(vector<vector<char> > &board)22     {23         for(int i = 0; i < 9; i++)24             for(int j = 0; j < 9; j++)25             {26                 if(board[i][j] == ‘.‘)27                 {28                     for(int k = 1; k <= 9; k++)29                     {30                         board[i][j] = ‘0‘ + k;31                         if(isValid(board,i,j) && solveSudokudfs(board))32                             return true;33                         board[i][j] = ‘.‘;34                     }35                     return false;36                 }37             }38         return true;39     }40     void solveSudoku(vector<vector<char> > &board) {41         // Note: The Solution object is instantiated only once.42         solveSudokudfs(board);43     }44 };

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.