Ruby Solution


  • 0
    R
    def count_battleships(board)
       battleship_count = 0
       board.each_with_index do |array, row|
           array.each_with_index do |char, col|
               if char == 'X'
                   mark_battleship(row, col, board)
                   battleship_count += 1
               end
           end
       end
        battleship_count
    end
    
    def mark_battleship(row, col, board)
        choices = [[1, 0], [-1, 0], [0, 1], [0, -1]]
        
        rowdir, coldir = choices.select do |choice|
            choicer, choicec = choice
            in_bounds?(row + choicer, col + choicec, board) && board[row + choicer][col + choicec] == 'X' 
        end.flatten
        
        return if rowdir.nil? || coldir.nil? 
        
        while in_bounds?(row, col, board) do
            if board[row][col] == 'X' 
                board[row][col] = '.'
                row += rowdir
                col += coldir
            else
                break
            end
        end
    end
    
    def in_bounds?(row, col, board)
        row >= 0 && row < board.length && col >= 0 && col < board.first.length
    end
            
    

    As a quick side note, I spent a good amount of time wondering why my initial bounds check:

    !board[row + choicer].nil && !board[row + choicer][col + choicec].nil?
    

    wasn't working. I completely forgot that with ruby array[-1] simply wraps around, and does not return nil... 🙄


Log in to reply
 

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