419. Battleships in a Board

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.