Cavity Map code in C#

You are given a square map of size $n \times n$. Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side (edge).

You need to find all the cavities on the map and depict them with the uppercase character X.

Input Format

The first line contains an integer, $n$, denoting the size of the map. Each of the following $n$ lines contains $n$ positive digits without spaces. Each digit (1-9) denotes the depth of the appropriate area.

Constraints

$1 \le n \le 100$

Output Format

Output $n$ lines, denoting the resulting map. Each cavity should be replaced with character X.

Sample Input

4
1112
1912
1892
1234

Sample Output

1112
1X12
18X2
1234

class Cavity_Map_Hackerrank
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt16(Console.ReadLine());
            int[,] arr = new int[n, n];
            string str = string.Empty;
            for (int i = 0, j = 0; i < n; ++i, j = 0)
            {
                str = Console.ReadLine();
                foreach (char ch in str)
                {
                    arr[i, j++] = Convert.ToInt16(ch - '0');
                }
            }

            int num = 0;
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    num = arr[i, j];

                    if (i == 0 || (i + 1) == n || j == 0 || (j + 1) == n)
                    {
                        Console.Write(arr[i, j]);
                    }
                    else if (num > arr[i, j + 1] && num > arr[i, j - 1] && num > arr[i - 1, j] && num > arr[i + 1, j])
                    {
                        Console.Write("X");
                    }
                    else
                    {
                        Console.Write(arr[i, j]);
                    }
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s