Battleships in a Board

MediumMath

Description

Count the number of battleships on a board. Battleships are represented by X and can only be placed horizontally or vertically. Return the result as an integer.

Examples

Input:board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output:2
Explanation:

One ship at [0,0], one vertical ship at column 3 (rows 0-2). Only count the top-left of each ship.

Input:board = [["X"]]
Output:1
Explanation:

A single 'X' represents one battleship of length 1. Since battleships can be a single cell, this counts as 1 battleship.

Input:board = [["X","X",".","X"],[".",".",".","X"],["X",".",".","."],["X",".","X","X"]]
Output:4
Explanation:

Four separate battleships: a horizontal 2-cell ship in row 1 (positions [0,0] and [0,1]), a vertical 2-cell ship in column 4 (positions [0,3] and [1,3]), a vertical 2-cell ship in column 1 (positions [2,0] and [3,0]), and a horizontal 2-cell ship in row 4 (positions [3,2] and [3,3]).

Constraints

  • 1 ≤ m, n ≤ 200

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!