LeetCode
每日一题 419.甲板上的战舰
https://leetcode-cn.com/problems/battleships-in-a-board/
分析
- 数据数量为:
1 <= m, n <= 200
dp 算法 - 总结题目:在甲板上有多少战舰,没有相邻战舰
- 战舰之间必然有一个分隔来区分战舰大小
题解
一次扫描 O(m*n)
dps数组记录战舰的位置,增加一个战舰,如果附近有一格有战舰的位置表示是是一个战舰的位置。
class Solution {
public int countBattleships(char[][] board) {
int m = board.length;
int n = board[0].length;
int ans = 0;
boolean [][]dp = new boolean[m][n];
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (board[i][j] != 'X' || dp[i][j]) { continue; }
// board[i][j] != 'X' 表示没有战舰
// dp[i][j] : 某个战舰的一部分
for (int x = i ; x < m && board[x][j] == 'X'; x ++)
dp[x][j] = true;
for (int y = j ; y < n && board[i][y] == 'X'; y++)
dp[i][y] = true;
// 标记战舰的位置
ans ++;
}
}
return ans;
}
}
一次扫描 O(1)
遇到一个战舰就增加ans,如果附近有’X’着直接跳过
class Solution {
public int countBattleships(char[][] board) {
int m = board.length;
int n = board[0].length;
int ans = 0;
for (int i = 0 ; i < m; i++){
for(int j = 0; j < n; j++){
if (i > 0 && board[i - 1][j] == 'X') { continue; }
if (j > 0 && board[i][j - 1] == 'X') { continue; }
// 如果附近有 'X' 表示是战舰的一部分,直接跳过
if (board[i][j] == 'X'){
ans += 1;
}
// 记录第一个出现的战舰
}
}
return ans;
}
}