← Home

419. Battleships in a Board

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
419

This is one of those problems where the clean idea matters more than the amount of code. For 419. Battleships in a Board, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are hasShip, countBattleships.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
03You receive a valid board, made of only battleships or empty slots.
04Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
05At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
06Example:
07X..X
08...X
09...X
10In the above board there are 2 battleships.
11Invalid Example:
12...X
13XXXX
14...X
15This is an invalid board that you will not receive - as battleships will always have a cell separating between them.
16Follow up:
17Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
18**/
19
20//Discuss by Code1404
21/**
22Whenever we encounter an "X" (ship) in the grid, check if its previous row/col has a Ship as well. 
23Remember from the question that "At least one horizontal or vertical cell separates between two battleships - 
24there are no adjacent battleships". So if its present, then its a continuation of an earlier ship, else its a new ship.
25**/
26
27//Your runtime beats 32.22 % of cpp submissions.
28//Your runtime beats 98.77 % of cpp submissions.
29class Solution {
30public:
31    bool hasShip(vector<vector<char>>& board, int r, int c){
32        if(r<0 || c<0 || r>=board.size() || c>=board[0].size())
33            return false;
34        return board[r][c]=='X';
35    }
36    int countBattleships(vector<vector<char>>& board) {
37        int count = 0;
38        
39        //Your runtime beats 32.22 % of cpp submissions.
40        for(int r = 0; r < board.size(); r++){
41            for(int c = 0; c < board[0].size(); c++){
42
43        //Your runtime beats 98.77 % of cpp submissions.
44        int rows = board.size();
45        int cols = board[0].size();
46        for(int r = 0; r < rows; r++){
47            for(int c = 0; c < cols; c++){
48                if(board[r][c]=='.') continue;
49                //we have counted the ship before
50                if(hasShip(board, r-1, c) || hasShip(board, r, c-1))continue;
51                count++;
52            }
53        }
54        return count;
55    }
56};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.