Created
May 11, 2016 19:30
-
-
Save jianminchen/589f05f5c87bb6e018de0a472d8a3b6f to your computer and use it in GitHub Desktop.
HackerRank - Connected Cell in a grid - using DFS, using ref value to track the count.
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.Threading.Tasks; | |
namespace connectedCellsInaGrid_May11_usingDFS_PassingRef | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int rows = Convert.ToInt32(Console.ReadLine()); | |
int cols = Convert.ToInt32(Console.ReadLine()); | |
int[,] arr = new int[rows, cols]; | |
for (int i = 0; i < rows; i++) | |
{ | |
string[] strA = Console.ReadLine().Split(' '); | |
for (int j = 0; j < cols; j++) | |
arr[i, j] = Convert.ToInt32(strA[j]); | |
} | |
Console.WriteLine(countConnectedCells(arr, rows, cols)); | |
} | |
public static int countConnectedCells(int[,] arr, int rows, int cols) | |
{ | |
int max = Int32.MinValue; | |
for (int i = 0; i < rows; i++) | |
for (int j = 0; j < cols; j++) | |
{ | |
int count = 0; | |
countConnectedCellsUsingDFS(arr, rows, cols, i, j, ref count); | |
max = count > max ? count : max; | |
} | |
return max; | |
} | |
private static void countConnectedCellsUsingDFS(int[,] arr, int rows, int cols, int startX, int startY, ref int registerNo) | |
{ | |
if (!inBound(startX, startY, rows, cols) || arr[startX, startY] == 0) | |
return ; | |
arr[startX, startY] = 0; | |
registerNo ++; | |
for (int i = -1; i <= 1; i++) | |
for (int j = -1; j <= 1; j++) | |
{ | |
int neighbor_X = startX + i; | |
int neighbor_Y = startY + j; | |
countConnectedCellsUsingDFS(arr, rows, cols, neighbor_X, neighbor_Y, ref registerNo); | |
} | |
return ; | |
} | |
private static bool inBound(int x, int y, int rows, int cols) | |
{ | |
return (x >= 0 && x < rows) && (y >= 0 && y < cols); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment