题目描述:
题解:
(1)暴力递归
class Solution(object):def find(self,i,j,board):if(board[i][j]=='.'):returnboard[i][j]='.'if( board[i-1][j]=='X' and i-1>0):self.find(i-1,j,board)if( j+1<len(board[0]) and board[i][j+1]=='X' ):self.find(i,j+1,board)if( i+1<len(board) and board[i+1][j]=='X'):self.find(i+1,j,board)if( board[i][j-1]=='X' and j-1>0):self.find(i,j-1,board)def countBattleships(self, board):count = 0for i in range(len(board)):for j in range(len(board[0])):if(board[i][j]=='X'):count+=1self.find(i,j,board)return count
(2)遍历扫描
class Solution:def countBattleships(self, board: List[List[str]]) -> int:ans = 0m, n = len(board), len(board[0])for i, row in enumerate(board):for j, ch in enumerate(row):if ch == 'X':row[j] = '.'for k in range(j + 1, n):if row[k] != 'X':breakrow[k] = '.'for k in range(i + 1, m):if board[k][j] != 'X':breakboard[k][j] = '.'ans += 1return ans
(3)枚举起点
class Solution {public int countBattleships(char[][] board) {int row = board.length;int col = board[0].length;int ans = 0;for (int i = 0; i < row; ++i) {for (int j = 0; j < col; ++j) {if (board[i][j] == 'X') {if (i > 0 && board[i - 1][j] == 'X') {continue;}if (j > 0 && board[i][j - 1] == 'X') {continue;}ans++;}}}return ans;}}


