题目描述:

image.png

image.png
image.png

题解:

(1)暴力递归

  1. class Solution(object):
  2. def find(self,i,j,board):
  3. if(board[i][j]=='.'):
  4. return
  5. board[i][j]='.'
  6. if( board[i-1][j]=='X' and i-1>0):
  7. self.find(i-1,j,board)
  8. if( j+1<len(board[0]) and board[i][j+1]=='X' ):
  9. self.find(i,j+1,board)
  10. if( i+1<len(board) and board[i+1][j]=='X'):
  11. self.find(i+1,j,board)
  12. if( board[i][j-1]=='X' and j-1>0):
  13. self.find(i,j-1,board)
  14. def countBattleships(self, board):
  15. count = 0
  16. for i in range(len(board)):
  17. for j in range(len(board[0])):
  18. if(board[i][j]=='X'):
  19. count+=1
  20. self.find(i,j,board)
  21. return count

(2)遍历扫描

  1. class Solution:
  2. def countBattleships(self, board: List[List[str]]) -> int:
  3. ans = 0
  4. m, n = len(board), len(board[0])
  5. for i, row in enumerate(board):
  6. for j, ch in enumerate(row):
  7. if ch == 'X':
  8. row[j] = '.'
  9. for k in range(j + 1, n):
  10. if row[k] != 'X':
  11. break
  12. row[k] = '.'
  13. for k in range(i + 1, m):
  14. if board[k][j] != 'X':
  15. break
  16. board[k][j] = '.'
  17. ans += 1
  18. return ans

(3)枚举起点

  1. class Solution {
  2. public int countBattleships(char[][] board) {
  3. int row = board.length;
  4. int col = board[0].length;
  5. int ans = 0;
  6. for (int i = 0; i < row; ++i) {
  7. for (int j = 0; j < col; ++j) {
  8. if (board[i][j] == 'X') {
  9. if (i > 0 && board[i - 1][j] == 'X') {
  10. continue;
  11. }
  12. if (j > 0 && board[i][j - 1] == 'X') {
  13. continue;
  14. }
  15. ans++;
  16. }
  17. }
  18. }
  19. return ans;
  20. }
  21. }