leetcode oj java Battleships in a Board
来源:互联网 发布:yum net snmp 编辑:程序博客网 时间:2024/06/05 16:07
一、问题描述:
Given an 2D board, count how many different 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.
二、解决方案:
要求任意两个战舰之间不会近邻,那么只需要找到战舰的头元素就可以了。头元素必须保证 tmp[i][j] == 'X' && tmp[i - 1][j] == '.' && tmp[i][j - 1] == '.' ,即本身为'X'但是左方和上方都为'.' 。 否则即为空的分割点或者是战舰的中间元素。我们新建一个tmp数组保存board,在最上边和最左边各加一列'.'。 满足one-pass的要求。
三、代码:
public class Solution { public int countBattleships(char[][] board) { int re = 0; int l = board.length; int w = board[0].length; char[][] tmp = new char[l + 1][w + 1]; for (int i = 0; i < l; i++) { for (int j = 0; j < w; j++) { tmp[i + 1][j + 1] = board[i][j]; } } for (int i = 0; i < w + 1; i++) { tmp[0][i] = '.'; } for (int i = 0; i < l + 1; i++) { tmp[i][0] = '.'; } for (int i = 1; i < l+1; i++) { for (int j = 1; j < w + 1; j++) { if (tmp[i][j] == 'X' && tmp[i - 1][j] == '.' && tmp[i][j - 1] == '.') re++; } } return re; }}
0 0
- leetcode oj java Battleships in a Board
- LeetCode OJ-419.Battleships in a Board
- Leetcode Battleships in a Board
- Battleships in a Board [Leetcode]
- LeetCode-Battleships in a Board
- 笔试题2. LeetCode OJ (2) Battleships in a Board
- LeetCode[419] Battleships in a Board
- LeetCode #419: Battleships in a Board
- 【leetcode】419. Battleships in a Board【E】
- Leetcode题解:419. Battleships in a Board
- leetcode 419 Battleships in a Board C++
- 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
- 正心,修身
- 深度学习初学对名词的记录
- 深入剖析ConcurrentHashMap(2)
- C语言经典例题(一)
- struts2配置文件
- leetcode oj java Battleships in a Board
- 与Xcode8的磨合
- javascript dom 编程艺术学习
- flume-ng的简单使用
- H264(NAL简介与I帧判断)
- dsp控制DM9000实现802.3数据收发第二篇,调试过程
- 常见面试概率问题
- SpannableStringBuilder实现图文混排
- Chrome 中的 JavaScript 断点设置和调试技巧