Created
April 17, 2016 00:48
-
-
Save jianminchen/9776d3d341d80c742c6c751f5ef00cb6 to your computer and use it in GitHub Desktop.
HackerRank - Connected Cell In a Grid - use queue, two dimension array, and also, not use recursive call, using loops instead.
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.Collections; | |
using System.IO; | |
using System.Numerics; | |
static class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int m = Convert.ToInt32(Console.ReadLine()); | |
int n = Convert.ToInt32(Console.ReadLine()); | |
int[,] matrix = new int[m, n]; | |
for (int r = 0; r < m; r++) | |
{ | |
string line = Console.ReadLine(); | |
int c = 0; | |
foreach (char ic in line) | |
{ | |
if (ic == '0' || ic == '1') | |
{ | |
int v = (int)(ic - '0'); | |
matrix[r, c++] = v; | |
} | |
} | |
} | |
Console.WriteLine(MaxRegion(m, n, matrix)); | |
} | |
static int MaxRegion(int m, | |
int n, | |
int[,] matrix) | |
{ | |
int maxRegion = Int32.MinValue; | |
for (int r = 0; r < m; r++) | |
{ | |
for (int c = 0; c < n; c++) | |
{ | |
int region = 0; | |
if (matrix[r, c] == 1) | |
{ | |
Queue queue = new Queue(); | |
int key = r * n + c; | |
matrix[r, c] = 2; | |
queue.Enqueue(key); | |
region = 0; | |
while (queue.Count > 0) | |
{ | |
key = (int)queue.Dequeue(); | |
int row = key / n; | |
int col = key % n; | |
region++; | |
for (int dr = -1; dr <= 1; dr++) | |
{ | |
for (int dc = -1; dc <= 1; dc++) | |
{ | |
int nrow = row + dr; | |
int ncol = col + dc; | |
if (nrow >= 0 && | |
nrow < m && | |
ncol >= 0 && | |
ncol < n && | |
matrix[nrow, ncol] == 1) | |
{ | |
key = nrow * n + ncol; | |
matrix[nrow, ncol] = 2; | |
queue.Enqueue(key); | |
} | |
} | |
} | |
} | |
} | |
if (region > maxRegion) | |
{ | |
maxRegion = region; | |
} | |
} | |
} | |
return maxRegion; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment