题目:判断数独是否合法



请判定一个数独是否有效。

该数独可能只填充了部分数字,其中缺少的数字用 . 表示。

您在真实的面试中是否遇到过这个题?
Yes
哪家公司问你的这个题? Airbnb Alibaba Amazon Apple Baidu Bloomberg Cisco Dropbox Ebay Facebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits
感谢您的反馈
样例

下列就是一个合法数独的样例。

注意

一个合法的数独(仅部分填充)并不一定是可解的。我们仅需使填充的空格有效即可。

说明

什么是 数独

  • http://sudoku.com.au/TheRules.aspx
  • http://baike.baidu.com/subview/961/10842669.htm
标签 Expand
矩阵

class Solution {
    /**
      * @param board: the board
        @return: wether the Sudoku is valid
      */
    public boolean isValidSudoku(char[][] board) {
                 boolean flag = true;
          if (board == null)
               return true;
          int[] f = new int[256];

          // row
          int row = 0;
          while (row < 9) {
               for (int i = 0; i < 256; i++) {
                    f[i] = 0;
               }
               for (int i = 0; i < 9; i++) {
                    if (board[row][i] != '.') {
                         if (f[board[row][i]] > 0) {
                              flag = false;
                              return flag;
                         } else {
                              f[board[row][i]] += 1;
                         }
                    }
               }
               row++;
          }
          // column
          int column = 0;
          while (column < 9) {
               for (int i = 0; i < 256; i++) {
                    f[i] = 0;
               }
               for (int i = 0; i < 9; i++) {
                    if (board[i][column] != '.') {
                         if (f[board[i][column]] > 0) {
                              flag = false;
                              return flag;
                         } else {
                              f[board[i][column]] += 1;
                         }
                    }
               }
               column++;
          }
          // blocks
          int r = 0;
          int c = 0;
          while (r < 9) {
               for (int i = 0; i < 256; i++) {
                    f[i] = 0;
               }
               for (int i = r; i < r+3; i++) {
                    for (int j = c; j < c+3; j++) {
                         if (board[i][j] != '.') {
                              if (f[board[i][j]] > 0) {
                                   flag = false;
                                   return flag;
                              } else {
                                   f[board[i][j]] += 1;
                              }
                         }
                    }
               }
               r += 3;
               c += 3;
          }
          return flag;
    }
};       

你可能感兴趣的:(题目:判断数独是否合法)