leetcode37解数独C++

1、题目

https://leetcode-cn.com/problems/sudoku-solver/

2、题意

题解1:暴力dfs 枚举每个不为’.'的位置1-9,进行特判;

class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
    	dfs(board,0,0);    
    }
    bool dfs(vector<vector<char>>&board,int i,int j)
    {
    	if(i==9) return true;//第10行的时候返回;
		if(j>=9) return dfs(board,i+1,0);//进行下一行
		if(board[i][j]=='.')
		{
			for(int k=0;k<9;k++) 
			{
				board[i][j] = char(k)+'1';
				if(is_valid(board,i,j))
				{
					if(dfs(board,i,j+1))
						return true;
				}
				board[i][j] = '.';
			}
		}
		else
			return dfs(board,i,j+1);
        return false;
	}
	bool is_valid(vector<vector<char>>&board,int i,int j)
	{
		for(int row=0;row<9;row++)
			if(row!=j&&board[i][j]==board[i][row]) return false;//列相等;
		for(int line=0;line<9;line++)
			if(line!=i&&board[i][j]==board[line][j]) return false;//行相等;
		for(int x=i/3*3;x<i/3*3+3;x++)
			for(int y=j/3*3;y<j/3*3+3;y++)
				if(i!=x&&j!=y&&board[i][j]==board[x][y])
					return false;//3*3的矩阵内斜着的相等; 
		return true;
	}
};

题解2:记录每一行每一列 每一个九宫格的状态

class Solution {
public:
    bool line[9][9],row[9][9],cell[3][3][9];
    void solveSudoku(vector<vector<char>>& board) {
    	for(int i=0;i<9;i++)
            for(int j=0;j<9;j++)
                if(board[i][j]!='.')
                {
                    int t = board[i][j]-'1';
                    line[i][t] = row[j][t] = cell[i/3][j/3][t] = true;
                }
        dfs(board,0,0);    
    }
    bool dfs(vector<vector<char>>&board,int i,int j)
    {
        if(j==9) i++,j=0;
    	if(i==9) return true;
        if(board[i][j]!='.')
            return dfs(board,i,j+1);
        else
        {
            for(int k=0;k<9;k++)
            {
                if(!line[i][k]&&!row[j][k]&&!cell[i/3][j/3][k])
                {
                    board[i][j] = (char)k+'1';
                    line[i][k] = row[j][k] = cell[i/3][j/3][k] = true;
                    if(dfs(board,i,j+1)) return true;
                    board[i][j] = '.';
                    line[i][k] = row[j][k] = cell[i/3][j/3][k] = false;
                }
            }
        }
        return false;
	}
    
};

你可能感兴趣的:(leetcode,leetcode,dfs,c++)