389. Valid Sudoku【LintCode java】

來源:互聯網
上載者:User

標籤:lintcode   file   character   empty   HERE   param   follow   font   png   

Description

Determine whether a Sudoku is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character ..

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Clarification

What is Sudoku?

  • http://sudoku.com.au/TheRules.aspx
  • https://zh.wikipedia.org/wiki/數獨
  • https://en.wikipedia.org/wiki/Sudoku
  • http://baike.baidu.com/subview/961/10842669.htm
Example

The following partially filed sudoku is valid.

 

解題:判斷數獨是否有效。如果每一行、每一列、每一個小方塊裡的數不重複,就算有效。當然,前提必須是1~9之間。此題空白部分是用“ . ”表示的,要注意一下。具體做法為,檢查行、列、方塊,把這些數拿出來,放在一個一維數組中,判斷這個一維數組裡的數,滿不滿足相應的條件。代碼如下:

public class Solution {    /**     * @param board: the board     * @return: whether the Sudoku is valid     */    public boolean isValidSudoku(char[][] board) {        // write your code here        char[]temp = new char[9];        for(int i = 0; i < 9; i++){            //檢查行            for(int j = 0; j < 9; j++){                temp[j] = board[i][j];            }            if(judge(temp) == false){                return false;            }            //檢查列            for(int j = 0; j < 9; j++){                temp[j] = board[j][i];            }            if(judge(temp) == false){                return false;            }        }        //小格子        for(int i = 0; i < 3; i++){            for(int j = 0; j < 3; j++){                int b = 0;                for(int k = 0 + i * 3; k < 3 + i * 3; k++){                    for(int m = 0 + j * 3; m < 3 + j * 3; m++){                        temp[b++] = board[k][m];                    }                }                if(judge(temp) == false)                return false;                            }        }        return true;    }    public boolean judge(char[]temp){        for(int i =0; i < 9; i++){            if(temp[i] > ‘9‘ || temp[i] < ‘1‘ ){                if(temp[i] != ‘.‘)                   return false;            }        }        for(int i = 1; i < 9; i++){            for(int j = 0; j < i; j++){                if(temp[i] == temp[j] ){                    if(temp[i] != ‘.‘)                        return false;                }            }        }        return true;    }}

 

389. Valid Sudoku【LintCode java】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.