Simple Ruby Solution Using Sets


  • 0
    R

    The idea is to initialize a set per collection of (1-9) characters that we care about (each row, each column, and each box) to ensure that there are no duplicate numbers, which would make the solution invalid.

    def is_valid_sudoku(board)
        boxes = Array.new(3) { Array.new(3) { Set.new } }
        rows = Array.new(9) { Set.new }
        cols = Array.new(9) { Set.new }
        
        board.each_with_index do |array, row|
            array.each_with_index do |num, col|
                next if num == '.'
                return false unless boxes[row/3][col/3].add?(num) && rows[row].add?(num) && cols[col].add?(num)
            end
        end
        true
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.