leetcode419. 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?

假设有一个2D板,在板上用X表示战舰,已知板上任意两个战舰体之间一定会用.隔开,因此不会出现两个X相邻的情况。现在要求用O(N)的时间复杂度和O(1)的空间复杂度来完成。

思路和代码

这题的思路非常清晰,我们只需要判断哪个X是战舰头即可,当我们遇到战舰头时,就将总战舰数加一,其余时候都继续遍历。战舰头即战舰的左侧和上侧没有其它的X

    public int countBattleships(char[][] board) {
        int count = 0;
        if(board == null || board.length == 0 || board[0].length == 0) return count;
        for(int i = 0 ; i<board.length ; i++) {
            for(int j = 0 ; j<board[i].length ; j++) {
                if(board[i][j] == 'X') {
                    if((i > 0 && board[i-1][j] == 'X') ||
                            (j > 0 && board[i][j-1] == 'X')) {
                        continue;
                    }
                    count++;
                }
            }
        }
        return count;
    }
    原文作者:后端开发
    原文地址: https://segmentfault.com/a/1190000018462146
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞