Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 18, 2016 21:02
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/574e77039f303cbbe3b72940236d5526 to your computer and use it in GitHub Desktop.
Save jianminchen/574e77039f303cbbe3b72940236d5526 to your computer and use it in GitHub Desktop.
Connected Cell In a Grid - using queue - write in 20 minutes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConnectedCellInaGridQueue2
{
class Program
{
static void Main(string[] args)
{
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().ToString();
int j = 0;
foreach (char c in s)
{
if (c == '0' || c == '1')
{
arr[i, j++] = c - '0';
}
}
}
Console.WriteLine(getMaxRegion(arr));
}
public static int getMaxRegion(int[,] arr)
{
int row = arr.GetLength(0);
int col = arr.GetLength(1);
int Max = Int32.MinValue;
for(int i=0; i< row; i++)
for (int j = 0; j < col; j++)
{
int val = getCount(arr, i, j);
if (val > Max)
Max = val;
}
return Max;
}
private static int getCount(int[,] arr, int posX, int posY)
{
int row = arr.GetLength(0);
int col = arr.GetLength(1);
if (arr[posX, posY] != 1)
return 0;
Queue<int> queue = new Queue<int>();
int key = posX * 10 + posY;
queue.Enqueue(key);
int count = 0;
while (queue.Count > 0)
{
int tmpKey = queue.Dequeue();
int tmpX = tmpKey / 10;
int tmpY = tmpKey % 10;
count++;
arr[tmpX, tmpY] = 2;
for(int dr=-1; dr<=1; dr++)
for (int dc = -1; dc <= 1; dc++)
{
int nX = tmpX + dr;
int nY = tmpY + dc;
if (isInRange(nX, nY, row, col) && arr[nX, nY] == 1)
{
arr[nX, nY] = 2; // make sure that no node will be added twice
queue.Enqueue(nX * 10 + nY);
}
}
}
return count;
}
private static bool isInRange(int nX, int nY, int row, int col)
{
if (nX >= 0 && nX < row && nY >= 0 && nY < col)
return true;
else
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment