当前位置:   article > 正文

力扣每日一题(十二——甲板上的战舰)_甲板上的战舰 csdn

甲板上的战舰 csdn

仅以此纪录每日LeetCode所刷题目

题目描述:

示例:

思路:

这道题一开始想到的思路是使用深度优先遍历算法来求解,但仔细读题之后发现这样做会比较麻烦,因为战舰只是横向排序或者纵向排序,因此我们不需要像深度优先遍历一样每次向四个方向同时进行搜索。在进行网格搜索的时候,每当我们遇到网格中的字符为“X”(代表此处有战舰时),我们只需要判断这个战舰的左面和上面是否存在战舰即可,若存在则代表这个网格存在于这个战舰的一行或者一列中。当这个战舰的左面和上面不存在战舰,则将计数器加一即可。

代码:

  1. class Solution:
  2. def countBattleships(self, board: List[List[str]]) -> int:
  3. def dfs(i,j,board):
  4. board[i][j] = "x"
  5. if i > 0 and board[i-1][j] == "X":
  6. dfs(i-1,j,board)
  7. if i > 0 and board[i][j-1] == "X":
  8. dfs(i,j-1,board)
  9. count = 0
  10. row = len(board)
  11. col = len(board[0])
  12. for i in range(row):
  13. for j in range(col):
  14. if board[i][j] == "X":
  15. if i>0 and board[i-1][j] == "X":
  16. continue
  17. if j>0 and board[i][j-1] == "X":
  18. continue
  19. count += 1
  20. return count
  1. class Solution:
  2. def countBattleships(self, board: List[List[str]]) -> int:
  3. def dfs(i,j,board):
  4. board[i][j] = "x"
  5. if i > 0 and board[i-1][j] == "X":
  6. dfs(i-1,j,board)
  7. if i > 0 and board[i][j-1] == "X":
  8. dfs(i,j-1,board)
  9. count = 0
  10. row = len(board)
  11. col = len(board[0])
  12. for i in range(row):
  13. for j in range(col):
  14. if board[i][j] == "X":
  15. if i<(len(board)-1) and board[i+1][j] == "X":
  16. continue
  17. if j<(len(board[0])-1) and board[i][j+1] == "X":
  18. continue
  19. count += 1
  20. return count

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/718344
推荐阅读
相关标签
  

闽ICP备14008679号