棋盘上的战舰

  两种方法都自己想出,一种是将舰队多余舰数删除,避免统计时被迷惑,另一种就是判断左边与上边是否为空来进行判断是否为舰队,注意:特殊的为第一行与第一列。

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
第一种
public int countBattleships(char[][] board) {
int count =0;
for(int i =0; i<board.length; i++){
for(int j =0; j<board[i].length; j++){
if(board[i][j]=='X'){
count++;
if(i+1<board.length&&board[i+1][j]=='X'){
for( int m = i+1;m<board.length;m++){
if(board[m][j]=='X'){
board[m][j]='.';
}else{
break;
}
}
}
if(j+1<board[i].length&&board[i][j+1]=='X'){
for( int m = j+1;m<board[i].length;m++){
if(board[i][m]=='X'){
board[i][m]='.';
}else{
break;
}
}
}
}
}

}
return count;
}

第二种:
public int countBattleships(char[][] board) {
int count =0;
for(int i =0; i<board.length; i++){
for(int j =0; j<board[i].length; j++){
if(board[i][j] =='X'){
if(i==0){
if(j==0){
count++;
}else{
if(board[i][j-1]=='.'){
count++;
}
}
}else{
if(j==0){
if(board[i-1][j]=='.'){
count++;
}
}else{
if(board[i-1][j]=='.'&&board[i][j-1]=='.'){
count++;
}
}
}

}
}

}
return count;
}