Leetcode 419: Battleships in a Board

grid47
grid47
Exploring patterns and algorithms
Sep 26, 2024 6 min read

A board game where ships glow softly as they are placed on the grid, each ship highlighted as it is positioned.
Solution to LeetCode 419: Battleships in a Board Problem

You are given a grid representing a battleship field, where ‘X’ marks the location of a part of a battleship and ‘.’ represents an empty sea cell. A battleship is either placed horizontally or vertically on the grid, with no adjacent battleships (there must be at least one empty cell between any two battleships). Your task is to count the number of distinct battleships on the grid.
Problem
Approach
Steps
Complexity
Input: The input is a 2D character grid where each cell contains either 'X' (part of a battleship) or '.' (empty sea).
Example: Input: board = [['X', '.', '.', 'X'], ['.', '.', '.', 'X'], ['.', '.', '.', 'X']]
Constraints:
• 1 <= m, n <= 200
• board[i][j] is either '.' or 'X'
Output: The output should be an integer representing the number of distinct battleships on the board.
Example: Output: 2
Constraints:
• The output is an integer indicating the number of distinct battleships.
Goal: The goal is to count the number of distinct battleships by identifying connected parts of 'X' (either horizontally or vertically).
Steps:
• Iterate through the grid cell by cell.
• For each 'X', check if it is the start of a new battleship (i.e., if there is no 'X' directly above or to the left of it).
• Count it as a new battleship if it is the start of one, and continue scanning the grid.
Goal: The problem constraints ensure that the grid size is manageable and the number of battleships is determined only by the layout of 'X' cells.
Steps:
• The grid can have a maximum size of 200x200.
• Each cell in the grid is either an 'X' or a '.' character.
Assumptions:
• The grid contains valid characters (either 'X' or '.').
• There is at least one row and one column in the grid.
Input: Example 1: Input: board = [['X', '.', '.', 'X'], ['.', '.', '.', 'X'], ['.', '.', '.', 'X']]
Explanation: In this case, there are two distinct battleships. The first one is placed horizontally from (0,0) to (0,3), and the second one is placed vertically from (0,3) to (2,3). Thus, the output is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus