zoukankan      html  css  js  c++  java
  • leetcode------Valid Sudoku

    标题: Valid Sudoku

    通过率:

    27.2%
    难度: 简单

    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.

    这个题做了一天。。。。醉了。。。这个题目其实不难。

    刚开始的时候我以为是求数独的解,给我吓一跳,简单题目都这么难了,然后我仔细一看就是求数独是否成立,那么就是满足三种情况

    1、一列内不能有重复。

    2、一行内不能重复。

    3、一个3×3方格内不能有重复。

    对于一行或者一列就是两重循环,但是对于求方格还是要画一下的。如下为九个方格的边界坐标(坐上到右下的遍历):

    (0,0)→(2,2) (0,3)→(2,5) (0,6)→(2,8)
    (3,0)→(5,2) (3,3)→(5,5) (3,6)→(5,8)
    (6,0)→(8,2) (6,3)→(8,5) (6,6)→(8,8)

    所以要写单独写一个函数去处理这个九个方格内的重复。

    以上求解的方法主要用到了hashset去处理重复。具体代码如下:

     1 public class Solution {
     2     public boolean isValidSudoku(char[][] board) {
     3         Set<Character> set=new HashSet<Character>();
     4         int x=0,y=0;
     5         for(int i=0;i<9;i++){
     6             set.clear();
     7             for(int j=0;j<9;j++){
     8                 if(board[i][j]=='.')continue;
     9                 if(set.contains(board[i][j]))return false;
    10                 else
    11                 set.add(board[i][j]);
    12                 
    13             }
    14         }
    15         for(int i=0;i<9;i++){
    16             set.clear();
    17             for(int j=0;j<9;j++){
    18                 if(board[j][i]=='.')continue;
    19                 if(set.contains(board[j][i]))return false;
    20                 else
    21                 set.add(board[j][i]);
    22             }
    23         }
    24         for(x=0;x<=6;x+=3){
    25             for(y=0;y<=6;y+=3){
    26                 if(!getRight(x,y,board))return false;
    27             }
    28         }
    29         
    30         return true;
    31     }
    32     public boolean getRight(int x,int y,char[][] board){
    33         Set<Character> tmp=new HashSet<Character>();
    34         int endx=x+3,endy=y+3,startx=x,starty=y;
    35         tmp.clear();
    36         for(x=startx;x<endx;x++)
    37         for(y=starty;y<endy;y++){
    38            if(board[x][y]=='.')continue;
    39             if(tmp.contains(board[x][y]))return false;
    40             else
    41             tmp.add(board[x][y]);
    42         }
    43         return true;
    44     }
    45 }

    写了一天是因为再处理两重循环时,第二层循环每次都要从头开始,不能不去处理,在代码里就是每次循环y时都要把y=starty操作。

  • 相关阅读:
    js和php中几种生成验证码的方式
    php中mysqli 处理查询结果集的几个方法
    100多个基础常用JS函数和语法集合大全
    js中的slice()、substring()、substr()、split()、join()、indexof()
    织梦dedecms标签大全总结
    0619-dedeCMS数据表
    0619-dedeCMS的安装、重装、目录说明、基本操作及注意事项
    0607-抽象类、抽象方法、接口、类的重载、类的自加载、对象的克隆
    0606-工厂模式、单例模式、DBDA的单例和完整功能
    js 替换/
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4250959.html
Copyright © 2011-2022 走看看