Skip to content

Commit de08839

Browse files
authoredFeb 16, 2017
Create 419. Battleships in a Board.java
1 parent 919d9f2 commit de08839

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
 

‎419. Battleships in a Board.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 1 scan, O(1) memory, w/o modifying input
2+
// works because of condition that ships are separate
3+
4+
public class Solution {
5+
public int countBattleships(char[][] board) {
6+
int nship = 0;
7+
8+
for (int r = 0; r < board.length; r++) {
9+
for (int c = 0; c < board[r].length; c++) {
10+
if (board[r][c] == 'X') {
11+
if (r == 0 && c == 0) {
12+
nship++;
13+
} else if (r == 0) {
14+
if (board[r][c-1] == '.') {
15+
nship++;
16+
}
17+
} else if (c == 0) {
18+
if (board[r-1][c] == '.') {
19+
nship++;
20+
}
21+
} else { // (r > 0 && c > 0)
22+
if (board[r-1][c] == '.' && board[r][c-1] == '.') {
23+
nship++;
24+
}
25+
}
26+
}
27+
}
28+
}
29+
30+
return nship;
31+
}
32+
}

0 commit comments

Comments
 (0)
Please sign in to comment.