Skip to content

Commit 0f2f250

Browse files
authored
Merge pull request #68 from Amrutha26/main
added java file
2 parents d3a9ff9 + cd0d89f commit 0f2f250

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

BattleshipsInABoard.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
}

0 commit comments

Comments
 (0)