Java HashMap example - Valid Sudoku

Byul·2023년 6월 14일

Java

목록 보기
9/10

source: https://leetcode.com/problems/valid-sudoku/

import java.util.HashSet;
import java.util.Set;

public class App {
    public static void main(String[] args) throws Exception {
        System.out.println(new Solution().isValidSudoku(new char[][] {
                { '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' }
        }));
    }
}

class Solution {

    public boolean isValidSudoku(char[][] board) {

        Set<Character> set = new HashSet<>();

        for (char[] row : board) {
            for (char cell : row) {
                if (cell == '.') continue;
                if (!set.add(cell)) return false;
            }
            set.clear();
        }

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char cell = board[j][i];
                if (cell == '.') continue;
                if (!set.add(cell)) return false;
            }
            set.clear();
        }

        for (int row = 0; row < 9; row += 3) {
            for (int col = 0; col < 9; col += 3) {
                for (int i = row; i < row + 3; i++) {
                    for (int j = col; j < col + 3; j++) {
                        char cell = board[i][j];
                        if (cell == '.') continue;
                        if (!set.add(cell)) return false;
                    }
                }
                set.clear();
            }
        }
        return true;
    }
}
profile
junior backend developer

0개의 댓글