Created
May 30, 2017 00:29
-
-
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.
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 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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.