LeetCode //C - 419. Battleships in a Board

419. Battleships in a Board

Given an m × n m \times n m×n matrix board where each cell is a battleship ‘X’ or empty ‘.’, return the number of the battleships on board.

Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 × k 1 \times k 1×k (1 row, k columns) or k × 1 k \times 1 k×1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).
 

Example 1:

在这里插入图片描述

Input: board = [[“X”,“.”,“.”,“X”],[“.”,“.”,“.”,“X”],[“.”,“.”,“.”,“X”]]
Output: 2

Example 2:

Input: board = [[“.”]]
Output: 0

Constraints:
  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is either ‘.’ or ‘X’.

From: LeetCode
Link: 419. Battleships in a Board


Solution:

Ideas:

1. Input Representation: The board is represented as a 2D array of strings, where each string contains the cells for that row.

2. Logic:

  • For each cell on the board, if it contains an ‘X’, check if it’s the top-left corner of a battleship by ensuring that there’s no ‘X’ immediately above or to the left.
  • This ensures that we count each battleship only once.

3. Edge Handling: The conditions if (i > 0 && board[i - 1][j] == ‘X’) and if (j > 0 && board[i][j - 1] == ‘X’) skip cells that are part of a previously counted battleship.

4. Output: The program prints the number of battleships on the board.

Code:
// Function to count the number of battleships on the board
int countBattleships(char** board, int boardSize, int* boardColSize) {
    
    
    int count = 0;
    
    // Iterate through the board
    for (int i = 0; i < boardSize; i++) {
    
    
        for (int j = 0; j < boardColSize[i]; j++) {
    
    
            // If the current cell contains a battleship ('X')
            // We check the top and left to avoid double counting
            if (board[i][j] == 'X') {
    
    
                // Ensure it is the top-left of the battleship
                if (i > 0 && board[i - 1][j] == 'X') continue;
                if (j > 0 && board[i][j - 1] == 'X') continue;
                
                // Count this as a new battleship
                count++;
            }
        }
    }
    
    return count;
}

猜你喜欢

转载自blog.csdn.net/navicheung/article/details/143089665