[Swift]LeetCode419. 甲板上的战舰 | Battleships in a Board

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:为敢(WeiGanTechnologies)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10333099.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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?

给定一个二维的甲板, 请计算其中有多少艘战舰。 战舰用 \'X\'表示,空位用 \'.\'表示。 你需要遵守以下规则:

给你一个有效的甲板,仅由战舰或者空位组成。

战舰只能水平或者垂直放置。换句话说,战舰只能由 1xN (1 行, N 列)组成,或者 Nx1 (N 行, 1 列)组成,其中N可以是任意大小。

两艘战舰之间至少有一个水平或垂直的空位分隔 - 即没有相邻的战舰。

示例 :

X..X ...X ...X

在上面的甲板中有2艘战舰。

无效样例 :

...X XXXX ...X

你不会收到这样的无效甲板 - 因为战舰之间至少会有一个空位将它们分开。

进阶:

你可以用一次扫描算法,只使用O(1)额外空间,并且不修改甲板的值来解决这个问题吗?

20ms

1 class Solution { 2 func countBattleships(_ board: [[Character]]) -> Int { 3 4 var battle = 0 5 6 for r in 0..<board.count{ 7 8 for c in 0..<board[0].count{ 9 10 if board[r][c] == "X"{ 11 var cellLeft = "." 12 var cellUp = "." 13 if c > 0 { 14 cellLeft = String(board[r][c-1]) 15 } 16 if r > 0{ 17 cellUp = String(board[r-1][c]) 18 } 19 20 if cellUp == "." && cellLeft == "."{ 21 battle += 1 22 } 23 } 24 25 } 26 } 27 28 return battle 29 } 30 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgdjjx.html