LeetCode——419. Battleships in a Board

题型:DFSpython

题目:算法

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:this

  • 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.code

Invalid Example:ip

...X
XXXX
...X

This is an invalid board that you will not receive - as battleships will always have a cell separating between them.leetcode

 

Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?get

 

Subscribe to see which companies asked this question.it

 

翻译(抄的):io

给定一个2维板,计算其中包含多少艘不一样的战舰。战舰用字符'X'表示,空白槽位用'.'表示。你应该假设以下规则:

  • 给定的板子是有效的,只包含战舰和空白槽位。
  • 战舰只能水平或者竖直放置。
  • 战舰的尺寸可能不一样。
  • 两艘战舰之间在水平方向或者竖直方向至少包含一个空间—不会存在相邻的战舰。

你的算法不该该修改board的值。

 

思路:

一种思路是简单遍历,由于题目给了方便,战舰之间没有相邻的(这里要理解,战舰是1-N个X组成,而不是一个)

 

另外一种思路是DFS深搜,归纳来说就是对每个点去深搜遍历它全部的相邻点,经过一个set来维护遍历过的点,这样每个点能够获得它相邻的全部点,即一艘战舰,再检查下一个点就能够先判断在不在set里,是否是已经属于统计过的某个战舰了。

 

代码(python):

class Solution(object):
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        found_set = set()
        ans = 0
        row_len = len(board)
        col_len = len(board[0] if row_len else [])
        def dfs(x, y):
            for movex, movey in zip((1,0,-1,0),(0,1,0,-1)):
                nx, ny = x + movex, y + movey
                if 0 <= nx < row_len and 0 <= ny < col_len:
                    if (nx,ny) not in found_set and board[nx][ny] == 'X':
                        found_set.add((nx, ny))
                        dfs(nx,ny)
                        
        for x in xrange(row_len):
            for y in xrange(col_len):
                if board[x][y] == 'X' and (x,y) not in found_set:
                    ans += 1
                    found_set.add((x,y))
                    dfs(x,y)
        return ans

 

A掉

相关文章
相关标签/搜索