comments | difficulty | edit_url | tags | |||
---|---|---|---|---|---|---|
true |
中等 |
|
给你一个大小为 m x n
的矩阵 board
表示棋盘,其中,每个单元格可以是一艘战舰 'X'
或者是一个空位 '.'
,返回在棋盘 board
上放置的 舰队 的数量。
舰队 只能水平或者垂直放置在 board
上。换句话说,舰队只能按 1 x k
(1
行,k
列)或 k x 1
(k
行,1
列)的形状放置,其中 k
可以是任意大小。两个舰队之间至少有一个水平或垂直的空格分隔 (即没有相邻的舰队)。
示例 1:
输入:board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]] 输出:2
示例 2:
输入:board = [["."]] 输出:0
提示:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j]
是'.'
或'X'
进阶:你可以实现一次扫描算法,并只使用 O(1)
额外空间,并且不修改 board
的值来解决这个问题吗?
我们可以遍历矩阵,找到每个战舰的左上角,即当前位置为 X
且上方和左方都不是 X
的位置,将答案加一。
遍历结束后,返回答案即可。
时间复杂度
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
m, n = len(board), len(board[0])
ans = 0
for i in range(m):
for j in range(n):
if board[i][j] == '.':
continue
if i > 0 and board[i - 1][j] == 'X':
continue
if j > 0 and board[i][j - 1] == 'X':
continue
ans += 1
return ans
class Solution {
public int countBattleships(char[][] board) {
int m = board.length, n = board[0].length;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == '.') {
continue;
}
if (i > 0 && board[i - 1][j] == 'X') {
continue;
}
if (j > 0 && board[i][j - 1] == 'X') {
continue;
}
++ans;
}
}
return ans;
}
}
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
int m = board.size(), n = board[0].size();
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == '.') {
continue;
}
if (i > 0 && board[i - 1][j] == 'X') {
continue;
}
if (j > 0 && board[i][j - 1] == 'X') {
continue;
}
++ans;
}
}
return ans;
}
};
func countBattleships(board [][]byte) (ans int) {
for i, row := range board {
for j, c := range row {
if c == '.' {
continue
}
if i > 0 && board[i-1][j] == 'X' {
continue
}
if j > 0 && board[i][j-1] == 'X' {
continue
}
ans++
}
}
return
}
function countBattleships(board: string[][]): number {
const m = board.length;
const n = board[0].length;
let ans = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (board[i][j] === '.') {
continue;
}
if (i && board[i - 1][j] === 'X') {
continue;
}
if (j && board[i][j - 1] === 'X') {
continue;
}
++ans;
}
}
return ans;
}