題型: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
1xN
(1 row, N columns) or Nx1
(N rows, 1 column), where N can be of any size.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掉