Resolved How can I calculate the number of ships' of battleship games in the array?

nataly

New member
Joined
Oct 11, 2021
Messages
1
Programming Experience
Beginner
Need to calculate the number of ships. Ships are presented as a “battleship” game.“1” represents a ship, “0” represents water. C#




C#:
namespace Ships
     {
     class Program
      {
      static int[,] ships = new int[10, 10] {
          { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, },
          { 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, },
          { 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, },
          { 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, },
          { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, },
          { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
          { 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, },
          { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
          { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, },
          { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, }
      };

      static void Main(string[] args)
      {
         int count = 0;

         // code write here
       
         Console.WriteLine(count);

         Console.ReadLine();
      }
     }
    }
 
Last edited:
In the official rules for the game of Battleship, you must have 5 ships and exactly 5 ships with the configuration of each ship being 2x1, 3x1, 3x1, 4x1, and 5x1 long respectively. Therefore, there is no need to count. Of course, using that argument with your CS teacher will likely get you a failing grade. :)

Anyway it looks like you aren't playing by the official ruleset. You'll have to do a process of elimination of finding the longest ship first and counting that and taking it off the board. Keep repeating that process. Of course, this will only work a long as you have an additional rule that two ships may not be directly adjacent to each other. (The official rules allow you to have them adjacent to each other.) If you are allowed to have ships adjacent to each other, then you'll likely have multiple solutions. Consider what happens when if the player puts three 1x1 ships right beside each other. The approach there is to do some recursion with backtracking to try out the various configurations that would satisfy the ship shapes.

Anyway, if you are guaranteed to not have ships adjacent to each other see this other thread:
 
Last edited:
Back
Top Bottom