[Leetcode] valid Sudoku

Source: Internet
Author: User

Determine if a Sudoku is valid, according to: Sudoku puzzles-the rules.

The sudoku board cocould 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.

Https://oj.leetcode.com/problems/valid-sudoku/

Train of Thought: according to the rules, first check the row, then check the column, and then check the 9 cells.

public class Solution {public boolean isValidSudoku(char[][] board) {int i;for (i = 0; i < 9; i++) {if (!isValid(board, i, i + 1, 0, 9))return false;}int j;for (j = 0; j < 9; j++) {if (!isValid(board, 0, 9, j, j + 1))return false;}for (i = 0; i < 9; i = i + 3)for (j = 0; j < 9; j = j + 3) {if (!isValid(board, i, i + 3, j, j + 3))return false;}return true;}private boolean isValid(char[][] board, int iBegin, int iEnd, int jBegin,int jEnd) {HashSet<Character> set = new HashSet<Character>();for (int i = iBegin; i < iEnd; i++)for (int j = jBegin; j < jEnd; j++) {if (set.contains(board[i][j]))return false;else if (board[i][j] != ‘.‘)set.add(board[i][j]);}return true;}public static void main(String[] args) {char[][] board = { { ‘5‘, ‘3‘, ‘.‘, ‘.‘, ‘7‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘ },{ ‘6‘, ‘.‘, ‘.‘, ‘1‘, ‘9‘, ‘5‘, ‘.‘, ‘.‘, ‘.‘ },{ ‘.‘, ‘9‘, ‘8‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘, ‘.‘ },{ ‘8‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘, ‘.‘, ‘.‘, ‘.‘, ‘3‘ },{ ‘4‘, ‘.‘, ‘.‘, ‘8‘, ‘.‘, ‘3‘, ‘.‘, ‘.‘, ‘1‘ },{ ‘7‘, ‘.‘, ‘.‘, ‘.‘, ‘2‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘ },{ ‘.‘, ‘6‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘2‘, ‘8‘, ‘.‘ },{ ‘.‘, ‘.‘, ‘.‘, ‘4‘, ‘1‘, ‘9‘, ‘.‘, ‘.‘, ‘5‘ },{ ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘8‘, ‘.‘, ‘.‘, ‘7‘, ‘9‘ } };System.out.println(new Solution().isValidSudoku(board));}}

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.