Created
April 18, 2016 00:42
-
-
Save jianminchen/fd909c3545e2081cf2dd2b6daea5900f to your computer and use it in GitHub Desktop.
HackerRank - connected Cell in a grid - return count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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