Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 17, 2016 01:11
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/c22abefe625ca4201d18841112a1a99a to your computer and use it in GitHub Desktop.
Save jianminchen/c22abefe625ca4201d18841112a1a99a to your computer and use it in GitHub Desktop.
use Tuple class, declare a shift array - very organized.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConnectedCell
{
using System.Reflection;
class Program
{
static int[] shifts = new int[] { -1, 0, 1 };
static void Main(string[] args)
{
int m, n;
m = int.Parse(Console.ReadLine());
n = int.Parse(Console.ReadLine());
int[,] table = new int[m, n];
for (int i = 0; i < m; i++)
{
var str = Console.ReadLine().Split(' ');
for (int j = 0; j < n; j++)
{
table[i, j] = int.Parse(str[j]);
}
}
int max = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (table[i, j] == 1)
{
max = Math.Max(RegionWeight(table, i, j, m, n), max);
}
}
}
Console.WriteLine(max);
}
private static int RegionWeight(int[,] table, int i, int j, int m, int n)
{
int count = 1;
table[i, j] = 0;
var coords = new List<Tuple<int, int>>();
coords.Add(new Tuple<int, int>(i, j));
while (coords.Count > 0)
{
var tmp = new List<Tuple<int, int>>();
foreach (var coord in coords)
{
for (int shiftI = 0; shiftI < shifts.Length; shiftI++)
{
if (InBounds(coord.Item1 + shifts[shiftI], m))
{
for (int shiftJ = 0; shiftJ < shifts.Length; shiftJ++)
{
if (InBounds(coord.Item2 + shifts[shiftJ], n)
&& table[coord.Item1 + shifts[shiftI], coord.Item2 + shifts[shiftJ]] == 1)
{
tmp.Add(new Tuple<int, int>(coord.Item1 + shifts[shiftI], coord.Item2 + shifts[shiftJ]));
table[coord.Item1 + shifts[shiftI], coord.Item2 + shifts[shiftJ]] = 0;
}
}
}
}
}
count += tmp.Count;
coords = tmp;
}
return count;
}
private static bool InBounds(int x, int max)
{
return x >= 0 && x < max;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment