设为首页 加入收藏

TOP

LeetCode36:Valid Sudoku
2015-11-21 00:59:36 来源: 作者: 【 】 浏览:1
Tags:LeetCode36: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.

?

这道题一看就是用空间来换取时间,正常情况下应该每行进行比较,每列进行比较,然后每一个网格进行比较,但是每个比较都有一个双层循环。

可以借助STL中的set来进行判断是否已经存在该元素,典型的空间换取时间的方法。

runtime:24ms

?

class Solution {
public:
    bool isValidSudoku(vector
  
   >& board) {
        unordered_set
   
     rows[9];//每一行一个set来判断改行是否存在重复元素 unordered_set
    
      columns[9];//每一列一个set用来判断该列是否存在重复元素 unordered_set
     
       grids[3][3];//每一个3*3网格一个set来判断该网格是否存在重复元素 for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(board[i][j]!='.') { char tmp=board[i][j]; if(!rows[i].insert(tmp).second||!columns[j].insert(tmp).second||!grids[i/3][j/3].insert(tmp).second) return false; } } } return true; } };
     
    
   
  
除了使用STL外由于这道题比较简单,可以使用和上面同样的方式自己定义一个掩码。

?

用一个int rows[9][9]来记录行的掩码

用一个int column[9][9]来记录列的掩码

用一个int gird[3][3][9]来记录网格的掩码。

runtime:12ms

运行时间少了一半!!!!

?

class Solution {
public:  
       bool isValidSudoku(vector
  
   >& board) {
             int rows[9][9]={0};
             int columns[9][9]={0};
             int grids[3][3][9]={0};
            
            for(int i=0;i<9;i++)
            {
                for(int j=0;j<9;j++)
                {
                    if(board[i][j]!='.')
                    {
                           char tmp=board[i][j];
                           int index=tmp-'1';
                           
                           if(rows[i][index]++)
                               return false;
                               
                           if(columns[j][index]++)
                                return false;
                                
                            if(grids[i/3][j/3][index]++)
                                return false;  
                    }
            
                }
            }
            return true;
            
        }
        
        
};



  


?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇sgu262:Symbol Recognition(状压.. 下一篇C++打印位数为n的所有数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: