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/ff415aef278e90f67464fdc168eeb28a to your computer and use it in GitHub Desktop.
Save jianminchen/ff415aef278e90f67464fdc168eeb28a to your computer and use it in GitHub Desktop.
Depth first search - using recursive, mocking experience - stack overflow error - Need to mark the node visited, avoid dead loop, no need to do memoization.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReachZero
{
class Program
{
static void Main(string[] args)
{
RunTestcase();
}
/// <summary>
/// arr = [3, 4, 2, 3, 0, 3, 1, 2, 1]
/// </summary>
public static void RunTestcase()
{
var numbers = new int[] { 3, 4, 2, 3, 0, 3, 1, 2, 1 };
var memo = new int[numbers.Length];
var result = CanReachZero(numbers, 0, memo);
}
/// <summary>
/// depth first search using recursive function,
/// need to mark the node after the visit to avoid deadloop.
///
/// </summary>
/// <param name="numbers"></param>
/// <param name="startIndex"></param>
/// <param name="memo"></param>
/// <returns></returns>
public static bool CanReachZero(int[] numbers, int startIndex, int[] memo)
{
if(numbers == null || numbers.Length == 0) return false;
int length = numbers.Length;
if(startIndex < 0 || startIndex > length - 1) return false;
if (numbers[startIndex] == 0){
return true;
}
if(memo[startIndex] != 0)
{
return memo[startIndex] == 1; // bug bit mask - speed ->
}
var visit = numbers[startIndex];
var goRight = startIndex + visit; //7 7
var goLeft = startIndex - visit; //5 3
bool result = false;
result = CanReachZero(numbers, goRight, memo);
if(!result)
{
result = CanReachZero(numbers, goLeft, memo);
}
memo[startIndex] = result? 1 : -1; // -1, 1, 0
return result; // true/ false
}
}
}
@jianminchen
Copy link
Author

Need to learn recursive function again! Do not mix the memoization with stack overflow error - dead loop issue - need to mark the node visit. It is more clear using a real stack, and then mark the visited nodes. Treat it as a chess board algorithm, 2 neighbors.

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