Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 17, 2016 22:25
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/b84a84ad3d4b69e153290e8fa528c288 to your computer and use it in GitHub Desktop.
Save jianminchen/b84a84ad3d4b69e153290e8fa528c288 to your computer and use it in GitHub Desktop.
Write same idea from code using queue
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConnectedCellInaGrid2
{
class Program
{
static void Main(string[] args)
{ // 2:40pm - 3:08pm
int row = Convert.ToInt32(Console.ReadLine());
int col = Convert.ToInt32(Console.ReadLine());
char[,] arr = new char[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;
j++;
}
}
}
int max = 0;
for(int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
int cur = getRegionCount(arr, i, j, row, col);
if (cur > max)
max = cur;
}
Console.WriteLine(max);
}
public static int getRegionCount(char[,] arr, int startX, int startY, int row, int col )
{
char c = arr[startX, startY];
if(c == '0' || c =='2')
return 0;
Queue<int> queue = new Queue<int>();
queue.Enqueue(getKey(startX, startY));
int[] dneighbor = { -1, 0, 1 };
int retCount = 0;
while(queue.Count > 0 )
{
int key1 =(int) queue.Dequeue();
int x = key1 / 10;
int y = key1 % 10;
if (arr[x, y] == '1') // need to add the check, otherwise, count more than once
{
arr[x, y] = '2'; // visited
retCount++;
}
for(int i=0; i< dneighbor.Length; i++)
for (int j = 0; j < dneighbor.Length; j++)
{
int nx = x + dneighbor[i];
int ny = y + dneighbor[j];
if (nx >= 0 && nx < row && ny >= 0 && ny < col && arr[nx, ny] == '1')
{
queue.Enqueue(nx * 10 + ny);
}
}
}
return retCount;
}
private static int getKey(int x, int y)
{
return 10 * x + y;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment