본문 바로가기
코딩테스트

LeetCode - 36. Valid Sudoku - swift

by vapor3965 2021. 8. 20.

목차

    https://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

     

    간단한 스도쿠 판별문제다.

    행, 열, 그리고 3*3 행렬안에 중복된 숫자가 있는지 판별하는 문제다.

     

    조건대로 행, 열을 모두 판별하면서, 3*3 행렬안에 중복된 숫자가 있는지 판별하는 것을 구현하면 된다.

    3*3행렬은,  i / 3, j / 3 으로 나눈값으로 판별했다. 

     

    class Solution {
        func isValidSudoku(_ board: [[Character]]) -> Bool {
            var square = Array(repeating: Array(repeating: Array(repeating: 0,count: 10), count: 9), count: 9)
            for i in 0..<9 {
                var rows = Array(repeating: 0, count: 10)
                var cols = Array(repeating: 0, count: 10)
                for j in 0..<9 {
                    if let num = Int(String(board[i][j])) {
                        rows[num] += 1
                        square[i/3][j/3][num] += 1
                        if rows[num] > 1 {
                            return false
                        }
                        if square[i/3][j/3][num] > 1 {
                            return false
                        }
                    }
                    if let num = Int(String(board[j][i])) {
                        cols[num] += 1
                        if cols[num] > 1 {
                            return false
                        }
                    }
                }
            }
            return true
        }
    }

    댓글