【LeetCode】419. Battleships in a Board
来源:互联网 发布:北京现代软件学院骗局 编辑:程序博客网 时间:2024/06/15 09:32
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) orNx1
(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...XIn the above board there are 2 battleships.
Invalid Example:
...XXXXX...XThis 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?
给定一个数组,X表示船 .表示空,求一共有多少条船。
其中:如果一个X的纵向或者横向上有X,则这俩是一条船。以此类推。
这道题有个附属条件是只用复杂度为 O(1)的额外内存并且不能修改入参。
思路:一个X的左边或者上面如果没有X,则船数+1;
/** * @param {character[][]} board * @return {number} */var countBattleships = function(board) { var count = 0; for(var i=0;i<board.length;i++){ for(var j=0;j<board[i].length;j++){ if(i>0&&j>0){ if(board[i-1][j]==='.'&&board[i][j-1]==='.'&&board[i][j]==="X"){ count++; } }else if(i>0&&j===0){ if(board[i-1][j]==='.'&&board[i][j]==="X"){ count++; } }else if(j>0&&i===0){ if(board[i][j-1]==='.'&&board[i][j]==="X"){ count++; } }else{ //(i===0&&j===0)===true if(board[i][j]==="X"){ count++; } } } } return count;};
阅读全文
0 0
- 【leetcode】419. Battleships in a Board【E】
- Leetcode题解:419. Battleships in a Board
- 419. [LeetCode]Battleships in a Board
- LeetCode 419. Battleships in a Board
- leetcode 419. Battleships in a Board
- LeetCode笔记:419. Battleships in a Board
- LeetCode 419. Battleships in a Board
- [leetcode]419. Battleships in a Board
- 【LeetCode】 419. Battleships in a Board
- LeetCode--419. Battleships in a Board
- LeetCode 419. Battleships in a Board
- [leetcode]419. Battleships in a Board
- Leetcode-419. Battleships in a Board
- 【LeetCode】419. Battleships in a Board
- LeetCode:419. Battleships in a Board
- [LeetCode]419. Battleships in a Board
- [LeetCode]419. Battleships in a Board
- 【LeetCode】419. Battleships in a Board
- masonry使用方法,masonry布局多控件横向或纵向一次性布局
- JPA 级联标签的解释 @Cascade
- slf4j初始化绑定源码分析
- 在centos7上为Jetty配置c3p0-mysql连接池.
- mac 编译ffmpeg真简单!
- 【LeetCode】419. Battleships in a Board
- 原型扩展1.2.7
- nginx模块开发实战
- 小程序的模态框和提示框
- Visual studio 2017中 Javascript无法智能提示的解决办法
- 判断今天是星期几 暴力枚举
- Retrofit各个注解的含义及作用
- [刷题]Codeforces Round #393(Div. 2)
- OJ提交题目中的语言选项里G++与C++的区别