Skip to content

Commit f73d1fa

Browse files
author
ruislan
committed
solved q419
1 parent 538bbeb commit f73d1fa

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/q/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ mod q412;
229229
mod q414;
230230
mod q415;
231231
mod q416;
232+
mod q419;
232233
mod q421;
233234
mod q423;
234235
mod q424;

src/q/q419.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
use crate::q::Solution;
2+
3+
#[allow(unused)]
4+
impl Solution {
5+
pub fn count_battleships(board: Vec<Vec<char>>) -> i32 {
6+
// 方法1
7+
// 计算战舰的规则是
8+
// 1。相连的算1艘战舰
9+
// 2。战舰要么横着,要么竖着,也就是说没有相交的情况
10+
// 这里我们可以只用迭代一次,当发现是'X'的时候,左边和上边都没有'X'的情况下,它也可以被计算
11+
// AC 0ms 3.8mb 27/27
12+
let rows = board.len();
13+
let cols = board[0].len();
14+
let mut ans = 0;
15+
for row in 0..rows {
16+
for col in 0..cols {
17+
if board[row][col] == 'X' {
18+
if row == 0 && col == 0 { ans += 1; }
19+
if row > 0 && col > 0 && board[row - 1][col] == '.' && board[row][col - 1] == '.' { ans += 1; }
20+
if row > 0 && col == 0 && board[row - 1][col] == '.' { ans += 1; }
21+
if row == 0 && col > 0 && board[row][col - 1] == '.' { ans += 1; }
22+
}
23+
}
24+
}
25+
ans
26+
}
27+
}

0 commit comments

Comments
 (0)