File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://leetcode.com/problems/battleships-in-a-board/
2+
3+ //Solution 1
4+ class Solution {
5+ public int countBattleships (char [][] board ) {
6+ int numBattleships = 0 ;
7+ for (int i =0 ; i <board .length ; i ++) {
8+ for (int j =0 ; j <board [i ].length ; j ++) {
9+ if (board [i ][j ] == '.' ) {
10+ continue ;
11+ }
12+
13+ if (i >0 && board [i -1 ][j ] == 'X' ) {
14+ continue ;
15+ }
16+
17+ if (j >0 && board [i ][j -1 ] == 'X' ) {
18+ continue ;
19+ }
20+
21+ numBattleships ++;
22+ }
23+ }
24+
25+ return numBattleships ;
26+ }
27+
28+ }
29+
30+
31+
32+ // Solution 2
33+
34+ class Solution {
35+ public int countBattleships (char [][] board ) {
36+ int numBattleships = 0 ;
37+ for (int i =0 ; i <board .length ; i ++) {
38+ for (int j =0 ; j <board [i ].length ; j ++) {
39+ if (board [i ][j ] == 'X' ) {
40+ numBattleships ++;
41+ sink (board , i , j );
42+ }
43+ }
44+ }
45+
46+ return numBattleships ;
47+ }
48+
49+ public void sink (char [][] board , int i , int j ) {
50+ if (i <0 || i >= board .length || j <0 || j >= board [i ].length || board [i ][j ] != 'X' ) {
51+ return ;
52+ }
53+
54+ board [i ][j ] = '.' ;
55+ sink (board , i +1 , j );
56+ sink (board , i -1 , j );
57+ sink (board , i , j +1 );
58+ sink (board , i , j -1 );
59+ }
60+ }
You can’t perform that action at this time.
0 commit comments