419. Battleships in a Board

Given 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:
  • You receive a valid board, made of only battleships or empty slots.
  • Battleships 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.
  • At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

Example:

X..X
...X
...X
In the above board there are 2 battleships.

Invalid Example:

...X
XXXX
...X
This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?

Rust Solution

struct Solution;

impl Solution {
    fn count_battleships(board: Vec<Vec<char>>) -> i32 {
        let n = board.len();
        let m = board[0].len();
        let mut res = 0;
        for i in 0..n {
            for j in 0..m {
                if Self::is_head(i, j, &board) {
                    res += 1;
                }
            }
        }
        res
    }

    fn is_head(i: usize, j: usize, board: &[Vec<char>]) -> bool {
        if board[i][j] == '.' {
            return false;
        }
        if i > 0 && board[i - 1][j] == 'X' {
            return false;
        }
        if j > 0 && board[i][j - 1] == 'X' {
            return false;
        }
        true
    }
}

#[test]
fn test() {
    let board = vec_vec_char![
        ['X', '.', '.', 'X'],
        ['.', '.', '.', 'X'],
        ['.', '.', '.', 'X']
    ];
    let res = 2;
    assert_eq!(Solution::count_battleships(board), res);
}

Having problems with this solution? Click here to submit an issue on github.