File tree Expand file tree Collapse file tree 2 files changed +28
-0
lines changed Expand file tree Collapse file tree 2 files changed +28
-0
lines changed Original file line number Diff line number Diff line change @@ -229,6 +229,7 @@ mod q412;
229229mod q414;
230230mod q415;
231231mod q416;
232+ mod q419;
232233mod q421;
233234mod q423;
234235mod q424;
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments