forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_419.java
83 lines (77 loc) · 2.75 KB
/
_419.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.fishercoder.solutions;
public class _419 {
public static class Solution1 {
/**
* credit: https://discuss.leetcode.com/topic/62970/simple-java-solution,
* <p>
* This solution does NOT modify original input.
* Basically, it only counts the top-left one while ignoring all other parts of one battleship,
* using the top-left one as a representative for one battle.
* This is achieved by counting cells that don't have 'X' to the left and above them.
*/
public int countBattleships(char[][] board) {
if (board == null || board.length == 0) {
return 0;
}
int count = 0;
int m = board.length;
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == '.') {
continue;//if it can pass this line, then board[i][j] must be 'X'
}
if (j > 0 && board[i][j - 1] == 'X') {
continue;//then we check if its left is 'X'
}
if (i > 0 && board[i - 1][j] == 'X') {
continue;//also check if its top is 'X'
}
count++;
}
}
return count;
}
}
public static class Solution2 {
/**
* My original solution, actually modified the input. I just undo it at the end.
*/
public int countBattleships(char[][] board) {
if (board == null || board.length == 0) {
return 0;
}
int result = 0;
int m = board.length;
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'X') {
result++;
dfs(board, i, j, m, n);
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == '#') {
board[i][j] = 'X';
}
}
}
return result;
}
private void dfs(char[][] board, int x, int y, int m, int n) {
if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'X') {
return;
}
if (board[x][y] == 'X') {
board[x][y] = '#';
}
dfs(board, x + 1, y, m, n);
dfs(board, x, y + 1, m, n);
dfs(board, x - 1, y, m, n);
dfs(board, x, y - 1, m, n);
}
}
}