Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 30, 2017 00:12
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/5d1fa73f2fc52d6fd3330611422e8f30 to your computer and use it in GitHub Desktop.
Save jianminchen/5d1fa73f2fc52d6fd3330611422e8f30 to your computer and use it in GitHub Desktop.
Depth first search - using recursive version - Julia fails recursive function again and again. The code is completed after mocking, she had a serious bug in her mocking practice.
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, string route)
{
if (numbers == null || numbers.Length == 0 )
{
return false;
}
int length = numbers.Length;
if (startIndex < 0 || startIndex > length - 1)
{
return false;
}
// base case - find 0 value
if (numbers[startIndex] == 0)
{
return true;
}
if (memo[startIndex] == 1)
{
return false;
}
memo[startIndex] = 1;
var visit = numbers[startIndex];
var goRight = startIndex + visit; //7 7
var goLeft = startIndex - visit; //5 3
return CanReachZero(numbers, goRight, memo, route + " " + goRight) ||
CanReachZero(numbers, goLeft, memo, route + " " + goLeft);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment