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.

答案
代码太长了,应该还有优化的空间

class Solution {
    private boolean isVertShip(char[][] board, int x, int y) {
        int topx = x - 1, topy = y;
        int botx = x + 1, boty = y;
        if(topx >= 0 && topx < board.length && topy >= 0 && topy < board[0].length && board[topx][topy] == 'X')
            return true;
        if(botx >= 0 && botx < board.length && boty >= 0 && boty < board[0].length && board[botx][boty] == 'X')
            return true;

        // no 'X' on top or bottom, must be a horizontal ship
        return false;
    }

    private boolean isShipEnd(char[][] board, int x, int y) {
        if(isVertShip(board, x, y)) {
            int botx = x + 1, boty = y;
            // if bottom is '.' or out of bounds, then this is the end of a ship
            return (botx >= board.length || board[botx][boty] == '.');
        }
        else {
            int rightx = x, righty = y + 1;
            return (righty >= board[0].length || board[rightx][righty] == '.');
        }
    }
    public int countBattleships(char[][] board) {
        if(board.length == 0) return 0;
        int ans = 0;
        // go one pass
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(board[i][j] == 'X') {
                    if(isShipEnd(board, i, j))
                        ans++;
                }
            }
        }
        return ans;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容