Count the Ships

Count the Ships 

Problem:

A sea is represented as an N*N matrix where # represents a part of a ship and - represents water. All the ships are surrounded by water. Series of # which are connected together forms a ship. The # can be connected to another # in any of the surrounding 8 cells to form a ship. The program must print the number of ships in the given map. 

Boundary Condition(s): 

1 <= N <= 100 

Input Format: 

The first line contains N. The next N lines contain N characters each. 

Output Format: 

The first line contains the count of the ship. 

Example Input/Output 1: 

Input: 

------ 

-###-- 

-###-- 

------ 

-####- 

-####- 

Output: 

2

Example Input/Output 2: 

Input: 

--#----- 

--#----- 

--#----- 

-----#-- 

------#- 

--#----# 

#####--- 

--#----- 

Output: 

Program:

#include<stdio.h>

#include <stdlib.h>

void fun(int n,char a[n][n], int i, int j)

{

    if(i<0 || j<0 || i>=n || j >= n || a[i][j] == 'v')

    {

        return;

    }

    if(a[i][j]=='#')

    {

        a[i][j] = 'v';

        fun(n,a,i+1,j);

        fun(n,a,i-1,j); 

        fun(n,a,i,j+1); 

        fun(n,a,i,j-1); 

        fun(n,a,i+1,j-1); 

        fun(n,a,i+1,j+1); 

        fun(n,a,i-1,j-1); 

        fun(n,a,i-1,j+1);

    }

}

int main()

{

int n; 

scanf("%d",&n);

char a[n][n]; 

for(int i=0;i<n;i++)

{

    for(int j=0;j<n;j++)

    {

        scanf(" %c ", &a[i][j]);

    }

}

int ships = 0;

for(int i=0;i<n;i++)

{

    for(int j=0;j<n;j++)

    {

        if(a[i][j] == '#')

        {

            ships++; 

            fun(n,a,i,j);

        }

    }

}

printf("%d\n",ships);

}

Comments

Popular posts from this blog

Pronic Integers in N - InfyTQ question

Count Strong Points - Accenture

Letters at position of multiples of a number