Skip to content

Instantly share code, notes, and snippets.

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/2279967c64a712fb138355b69a6201dd to your computer and use it in GitHub Desktop.
Save jianminchen/2279967c64a712fb138355b69a6201dd to your computer and use it in GitHub Desktop.
HackerRank - Connected Cells in a Grid - using DFS - using recursive functions, no queue, recursive function returns value
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace connectedCellsInaGrid_May11_usingDFS
{
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 value = countConnectedCellsUsingDFS(arr, rows, cols, i, j);
max = value > max ? value : max;
}
return max;
}
private static int countConnectedCellsUsingDFS(int[,] arr, int rows, int cols, int startX, int startY)
{
if (!inBound(startX, startY, rows, cols) || arr[startX, startY] == 0)
return 0;
arr[startX, startY] = 0;
int count = 1;
for(int i=-1;i<=1; i++)
for (int j = -1; j <= 1; j++)
{
int neighbor_X = startX + i;
int neighbor_Y = startY + j;
count += countConnectedCellsUsingDFS(arr, rows, cols, neighbor_X, neighbor_Y);
}
return count;
}
private static bool inBound(int x, int y,int rows, int cols)
{
return (x >= 0 && x < rows) && (y >= 0 && y < cols);
}
}
}
@jianminchen
Copy link
Author

Writing is very smoothly. In the code review, Julia found out that inBound four arguments does not match the calling function, so she quickly updated. Most important, it is to go over every line, every variable, every logic checking, and be patient, make sure that no mistakes, typing error, logic error, things to improve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment