LeetCode 37. Sudoku Solver
Posted hankunyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 37. Sudoku Solver相关的知识,希望对你有一定的参考价值。
经典backtracing的问题。我们可以记录每行,每列,每个box那些数字出现过,快速判断当前填入的数字是否有重复。
class Solution public: vector<vector<bool>> rowhash; // rowhash[row][1~9] - if the number has been taken in row vector<vector<bool>> colhash; // colhash[col][1~9] - if the number has been taken in col vector<vector<bool>> boxhash; // box are indexed by 0~8, from left to right, top to bottom void solveSudoku(vector<vector<char>>& board) int m=board.size(), n=m==0?0:board[0].size(); if (m==0 || n==0) return; rowhash.resize(9,vector<bool>(10,false)); colhash.resize(9,vector<bool>(10,false)); boxhash.resize(9,vector<bool>(10,false)); for (int i=0;i<m;++i) for (int j=0;j<n;++j) if (board[i][j]==‘.‘) continue; int num=board[i][j]-‘0‘; rowhash[i][num] = true; colhash[j][num] = true; boxhash[i/3*3+j/3][num] = true; // i/3, j/3 backtrack(board,0,0); bool backtrack(vector<vector<char>> &board, int i, int j) if (i==9) return true; if (board[i][j]!=‘.‘) auto [next_i,next_j] = nextPos(i,j); return backtrack(board,next_i,next_j); else // select a number to fill in the blank for (int k=1;k<=9;++k) if (!rowhash[i][k] && !colhash[j][k] && !boxhash[i/3*3+j/3][k]) board[i][j] = k+‘0‘; rowhash[i][k] = colhash[j][k] = boxhash[i/3*3+j/3][k] = true; auto [next_i,next_j] = nextPos(i,j); if (backtrack(board,next_i,next_j)) return true; board[i][j] = ‘.‘; rowhash[i][k] = colhash[j][k] = boxhash[i/3*3+j/3][k] = false; return false; pair<int,int> nextPos(int i, int j) if (j==8) return i+1,0; else return i,j+1; ;
上述方法是dfs(i,j),导致没到一行的末尾要换行,比较繁琐。
可以把所有空格都放到一个vector里,dfs这个vector的下标即可。
以上是关于LeetCode 37. Sudoku Solver的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 37. Sudoku Solver —— 解数独
LeetCode 37 Sudoku Solver(求解数独)