Skip to content

Latest commit

 

History

History
94 lines (72 loc) · 2.51 KB

_419. Battleships in a Board.md

File metadata and controls

94 lines (72 loc) · 2.51 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 24, 2024

Last updated : June 24, 2024


Related Topics : Array, Depth-First Search, Matrix

Acceptance Rate : 76.25 %


Solutions

Python

class Solution:
    def countBattleships(self, board: List[List[str]]) -> int:
        counter = 0

        # find corners
        for r in range(len(board)) :
            for c in range(len(board[0])) :
                if board[r][c] == 'X' \
                    and (c == 0 or board[r][c - 1] == '.') \
                    and (r == 0 or board[r - 1][c] == '.'):
                    counter += 1

        return counter

C

int countBattleships(char** board, int boardSize, int* boardColSize) {
    int counter = 0;

    for (int r = 0; r < boardSize; r++) {
        for (int c = 0; c < boardColSize[0]; c++) {
            if (board[r][c] == 'X'
                && (c == 0 || board[r][c - 1] == '.')
                && (r == 0 || board[r - 1][c] == '.'))
                counter++;
        }
    }
    return counter;
}
void removeShip(char** board, int boardSize, int* boardColSize, int x, int y) {
    if (x < 0 || x >= boardSize || y < 0 || y >= boardColSize[0] || board[x][y] == '.') {
        return;
    }

    board[x][y] = '.';

    removeShip(board, boardSize, boardColSize, x + 1, y);
    removeShip(board, boardSize, boardColSize, x - 1, y);
    removeShip(board, boardSize, boardColSize, x, y + 1);
    removeShip(board, boardSize, boardColSize, x, y - 1);
}

int countBattleships(char** board, int boardSize, int* boardColSize) {
    int counter = 0;

    for (int i = 0; i < boardSize; i++) {
        for (int j = 0; j < boardColSize[0]; j++) {
            if (board[i][j] == 'X') {
                counter++;
                removeShip(board, boardSize, boardColSize, i, j);
            }
        }
    }
    return counter;
}