Indra Bayu
BAN USERMy solution in C#
int CountArea(char [,] m, int N, char color, Tuple<int,int> s) {
if(m == null || N < 1)
throw new Exception("Wrong input");
var pending = new Queue<Tuple<int,int>>();
var done = new HashSet<Tuple<int,int>>();
Func<Tuple<int,int>, bool> eval = (candidate) => {
int a = candidate.Item1, b = candidate.Item2;
if(a >= 0 && a < N && b >= 0 && b < N &&
m[a,b] == color &&
!done.Contains(candidate) &&
!pending.Contains(candidate)) {
done.Add(candidate);
return true;
}
else
return false;
};
int i,j;
pending.Enqueue(s);
while(pending.Count != 0) {
var curr = pending.Dequeue();
if(eval(curr)) {
i = curr.Item1;
j = curr.Item2;
pending.Enqueue(new Tuple<int,int>(i-1, j)); //1. UP
pending.Enqueue(new Tuple<int,int>(i, j+1)); //2. RIGHT
pending.Enqueue(new Tuple<int,int>(i+1, j)); //3. DOWN
pending.Enqueue(new Tuple<int,int>(i, j-1)); //4. LEFT
}
}
return done.Count;
}
While the main method can be something like this:
static void Main(string[] args)
{
int N = 6;
char[,] matrix = new char[N,N];
string [] lines = new string [N];
lines[0] = "000000";
lines[1] = "0RRRR0";
lines[2] = "0R00R0";
lines[3] = "0R00R0";
lines[4] = "0RRRR0";
lines[5] = "000000";
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
matrix[i, j] = lines[i][j];
}
}
Console.WriteLine(CountArea(matrix, N, '0', new Tuple<int, int>(0, 0)));
}
--
Indra Bayu
Vrije Universiteit Brussel
My solution in C#
char [] LongestInDictionary(List<char[]> entries, char [] stocks) {
if(entries == null || entries.Count == 0 ||
stocks == null || stocks.Length == 0)
throw new Exception("wrong input");
var dict = new Dictionary<char, int>();
foreach(var stock in stocks) {
if(!dict.TryAdd(stock, 1))
dict[stock]++;
}
char [] longest = null;
foreach(var entry in entries) {
var copy = dict.ToDictionary();//cloning
bool ok = true;
foreach(var chr in entry) {
if(!dict.ContainsKey(chr) || dict[chr] == 0) {
ok = false;
break;
}
dict[chr]--;
}
if(ok) {
if(longest == null || entry.Length > longest.Length)
longest = entry;
}
}
return longest;
}
If it's not a doubly linked list, then I think it's impossible.
- Indra Bayu May 12, 2014