题目描述:
用一次遍历,找出来有多少个不相连的X
第一遍,自己写的
def countBattleships(self, board: List[List[str]]) -> int:
res = 0
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 'X':
res += 1
board[i][j] = 'Y'
for m in range(i + 1,len(board)):
if board[m][j] == 'X':
board[m][j] = 'Y'
else:
break
for n in range(j + 1,len(board[0])):
if board[i][n] == 'X':
board[i][n] = 'Y'
else:
break
elif board[i][j] == 'Y':
board[i][j] == 'X'
return res
看完答案,果然自己又弟弟了
只要遍历的时候,计数:计最左上角的就可以
关键在于:最左上角的条件怎么去写?
观察可以得出:最左上角的元素或者是 上方是 ‘.’ 或者是左方是'.' (因为不是最左上角的元素,上方或者左方必定是x)
同时,如果最左上角的元素, index == 0 也要考虑进来。
代码如下:
def countBattleships(self, board: List[List[str]]) -> int:
res = 0
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 'X' and (i == 0 or board[i-1][j] == '.') and (j == 0 or board[i][j-1] == '.'):
res += 1
return res