알고리즘/[ LeetCode ]

[ LeetCode ][JAVA][36] Valid Sudoku(스도쿠 판별)

kim.svadoz 2020. 9. 24. 10:54
728x90
반응형

leetcode.com/problems/valid-sudoku/

 

Valid Sudoku - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
    image-20200924105136338
    A partially filled sudoku which is valid.

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

제한사항

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.
  • The given board contain only digits 1-9 and the character '.'.
  • The given board size is always 9x9.

접근

백트래킹을 이용한 스도쿠 판별!!

코드

import java.util.Arrays;

class Solution {

	public static void main(String[] args) {
		//주어진 스도쿠가 유효한 스도쿠인지 확인하는 메소드.
	}
	
	public static boolean isValidSudoku(char[][] board) {
		boolean[] b = new boolean[9];
		//룰의 종류, 가로/세로/섭그리드
		for(int i=0; i<3; i++) {
			//한줄의 규칙
			for(int j=0; j<9; j++) {
				Arrays.fill(b, false);
				for(int k=0; k<9; k++) {
					char cur= '.';
					if(i == 0) {
						//가로
						cur=board[j][k];
					}else if(i == 1) {
						//세로
						cur=board[k][j];
					}else {
						//섭그리드
						cur = board[j/3*3 + k/3][j%3*3 + k%3];
					}
					if(cur=='.') continue;
					int val = Character.getNumericValue(cur);
					if(b[val-1]) return false;
					b[val-1] = true;
				}
			}
		}
		return true;
	}
}
728x90
반응형