intcountBattleships(char** board, int boardSize, int* boardColSize){ int row = boardSize; int col = boardColSize[0]; int ans = 0; for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { if (board[i][j] == 'X') { board[i][j] = '.'; for (int k = j + 1; k < col && board[i][k] == 'X'; ++k) { board[i][k] = '.'; } for (int k = i + 1; k < row && board[k][j] == 'X'; ++k) { board[k][j] = '.'; } ans++; } } } return ans; }
var countBattleships = function(board) { const row = board.length; const col = board[0].length; let ans = 0; for (let i = 0; i < row; ++i) { for (let j = 0; j < col; ++j) { if (board[i][j] === 'X') { board[i][j] = '.'; for (let k = j + 1; k < col && board[i][k] === 'X'; ++k) { board[i][k] = '.'; } for (let k = i + 1; k < row && board[k][j] === 'X'; ++k) { board[k][j] = '.'; } ans++; } } } return ans; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funccountBattleships(board [][]byte) (ans int) { m, n := len(board), len(board[0]) for i, row := range board { for j, ch := range row { if ch == 'X' { row[j] = '.' for k := j + 1; k < n && row[k] == 'X'; k++ { row[k] = '.' } for k := i + 1; k < m && board[k][j] == 'X'; k++ { board[k][j] = '.' } ans++ } } } return }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defcountBattleships(self, board: List[List[str]]) -> int: ans = 0 m, n = len(board), len(board[0]) for i, row inenumerate(board): for j, ch inenumerate(row): if ch == 'X': row[j] = '.' for k inrange(j + 1, n): if row[k] != 'X': break row[k] = '.' for k inrange(i + 1, m): if board[k][j] != 'X': break board[k][j] = '.' ans += 1 return ans
复杂度分析
时间复杂度:$O(m \times n \times \max(m,n))$,其中 $m$ 是矩阵的行数,$n$ 是矩阵的列数,我们对于矩阵的每个位置都会遍历一遍以该位置所在的行和列。