Given an 2D board, count how many different battleships is in it. ‘X‘
the battleships is represented with s, empty slots is represented with ‘.‘
s. Assume the following rules:
- You receive a valid board, made of the only battleships or empty slots.
- Battleships can is only placed horizontally or vertically. In other words, they can is only made of the shape
1xN
(1 row, n columns) or Nx1
(n rows, 1 column), where n can is Any size.
- At least one horizontal or vertical cell separates between and Battleships-there are no adjacent battleships.
Example:
X.. X... X... X
In the above board there is 2 battleships.
Invalid Example:
... Xxxxx... X
This was an invalid board so you'll not receive-as battleships would always have a cell separating between them.
Find out how many boats, horizontal or vertical, are not separated by a boat, with at least one empty point between the ships
Problem Solving Ideas:
Traversing a two-dimensional array, each traversing to a position, only need to consider whether its left and top position is x.
1 intCountbattleships (Char* * Board,intBoardrowsize,intboardcolsize) {2 inti,j;3 intCount=0;4 for(i=0; i<boardrowsize;i++)5 for(j=0; j<boardcolsize;j++)6 if(board[i][j]=='X')7 {8 if(i==0)9 {Ten if(j==0|| board[i][j-1]=='.') Onecount++; A } - Else - { the if((j==0&&board[i-1][j]=='.')|| (board[i-1][j]=='.'&&board[i][j-1]=='.')) -count++; - } - } + returncount; - } + //as you traverse through each element, you only need to consider whether it is '. ' in front and above. Can be
419. Battleships in a Board