前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode419. Battleships in a Board

leetcode419. Battleships in a Board

作者头像
眯眯眼的猫头鹰
发布2019-03-20 10:56:25
3560
发布2019-03-20 10:56:25
举报

题目要求

代码语言:javascript
复制
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

代码语言:javascript
复制
    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;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档