Valid Sudoku 및 Sudoku Solver

3500 단어 LeetCode递归sudoku
제목 1: Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character  '.' .
A partially filled sudoku which is valid.
Note: A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. 사고방식: 순환적으로 매 줄, 매 열, 각 네모난 블록이 효과가 있는지 판단한다
class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
    	vector<bool> check(9,false);
    	int i,j,block;
    	for(i = 0;i < 9;++i)// 
    	{
    		check.assign(9,false);
    		for(j = 0; j < 9;++j)
    		{
    			if(board[i][j] == '.')continue;
    			if(check[board[i][j] - '0'])return false;
    			check[board[i][j] - '0'] = true;
    		}
    	}
    	for(i = 0;i < 9;++i)// 
    	{
    		check.assign(9,false);
    		for(j = 0;j < 9;++j)
    		{
    			if(board[j][i] == '.')continue;
    			if(check[board[j][i] - '0'])return false;
    			check[board[j][i] - '0'] = true;
    		}
    	}
    	for(block = 0;block < 9;++block)// 
    	{
    		int startx = (block/3)*3;// 
    		int starty = (block%3)*3;
    		check.assign(9,false);
    		for(i = startx; i < startx+3;++i)
    		{
    			for(j = starty;j < starty+3;++j)
    			{
    				if(board[i][j] == '.')continue;
    				if(check[board[i][j] - '0'])return false;
    				check[board[i][j] - '0'] = true;
    			}
    		}
    	}
    	return true;
    }
};

제목 2: 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. 사고방식: 모든 공백점이 효과가 있는지 테스트한다. n황후와 유사하다
class Solution {
public:
    bool check_valid(vector<vector<char> >& board,int row,int col)
    {
    	int i,j;
    	for(i = 0;i < 9;++i)// 
    	{
    		if(i != col && board[row][i] == board[row][col])return false;
    	}
    	for(i = 0;i < 9;++i)// 
    	{
    		if(i != row && board[i][col] == board[row][col])return false;
    	}
    	for(i = (row / 3)*3;i < (row /3 +1)*3;++i)// 
    	{
    		for(j = (col / 3)*3;j < (col / 3+1)*3;++j)
    		{
    			if(i != row && j != col && board[i][j] == board[row][col])return false;
    		}
    	}
    	return true;
    }
    
    bool isValidSudoku(vector<vector<char> >& board)
    {
    	int row,col;
    	for(row = 0;row < 9;++row)
    	{
    		for(col = 0;col < 9;++col)
    		{
    			if(board[row][col] == '.')
    			{
    			int i;
    			for(i = 1;i <= 9;++i)// 
    			{
    				board[row][col] = i + '0';
    				if(check_valid(board,row,col) && isValidSudoku(board))return true;
    			}
    			board[row][col] = '.';
    			return false;
    			}
    		}
    	}
    	return true;
    }
    void solveSudoku(vector<vector<char> > &board) {
    	isValidSudoku(board);
    }

};

좋은 웹페이지 즐겨찾기