Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 18, 2016 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/fd909c3545e2081cf2dd2b6daea5900f to your computer and use it in GitHub Desktop.
Save jianminchen/fd909c3545e2081cf2dd2b6daea5900f to your computer and use it in GitHub Desktop.
HackerRank - connected Cell in a grid - return count
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConnectCellInaGrid_Count
{
class Program
{
static void Main(string[] args)
{ // 2:40pm - 3:08pm
int row = Convert.ToInt32(Console.ReadLine());
int col = Convert.ToInt32(Console.ReadLine());
int[,] arr = new int[row, col];
for (int i = 0; i < row; i++)
{
string s = Console.ReadLine();
int j = 0;
foreach (char c in s)
{
if (c == '0' || c == '1')
{
arr[i, j] = c -'0';
j++;
}
}
}
int max = 0;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
int cur = getRegionCount(arr, i, j);
if (cur > max)
max = cur;
}
Console.WriteLine(max);
}
public static int getRegionCount(int[,] arr, int i, int j)
{
int row = arr.GetLength(0);
int col = arr.GetLength(1);
if (isInRange(i, j, row, col) && arr[i, j] == 1)
{
arr[i, j] = 2;
return 1 +
getRegionCount(arr, i - 1, j - 1) +
getRegionCount(arr, i - 1, j) +
getRegionCount(arr, i - 1, j + 1) +
getRegionCount(arr, i, j - 1) +
getRegionCount(arr, i, j + 1) +
getRegionCount(arr, i + 1, j - 1) +
getRegionCount(arr, i + 1, j) +
getRegionCount(arr, i + 1, j + 1);
}
else
return 0;
}
private static bool isInRange(int i, int j, int row, int col)
{
if (i >= 0 && i < row && j >= 0 && j < col)
return true;
else
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment