Skip to content

Instantly share code, notes, and snippets.

@lulalachen
Last active August 24, 2017 16:33
Show Gist options
  • Save lulalachen/5ceb32e18d4c7b0c236dba9980340a02 to your computer and use it in GitHub Desktop.
Save lulalachen/5ceb32e18d4c7b0c236dba9980340a02 to your computer and use it in GitHub Desktop.
class Solution(object):
def getShipCountInRow(self, row):
ships = 0
isShipContinuous = False
for txt in row:
if txt == u'X':
isShipContinuous = True
if isShipContinuous and txt == u'.':
isShipContinuous = False
ships += 1
if isShipContinuous:
ships += 1
return ships
def getContinueShipCount(self, row1, row2):
result = []
for index in range(len(row1)):
if row1[index] == row2[index] == u'X':
result.append(u'X')
else:
result.append(u'.')
return self.getShipCountInRow(result)
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
ships = self.getShipCountInRow(board[0])
for index, row in enumerate(board[1:]):
tempShips = self.getShipCountInRow(row)
print(index, row, tempShips)
previousRow = board[index]
tempShips -= self.getContinueShipCount(row, previousRow)
ships += tempShips
return ships
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment