Last active
September 22, 2019 17:09
-
-
Save KylePiira/8df1f3071a422ea58cc06cb067df86e1 to your computer and use it in GitHub Desktop.
Problem 2.1.7c
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
public class P217 { | |
public static void main(String[] args) throws Exception { | |
// Example | |
boolean[][] r = { | |
{false, false, false, true, false, false}, | |
{false, false, true, false, false, false}, | |
{false, true, false, false, false, false}, | |
{false, false, true, false, false, false}, | |
{false, false, false, false, false, true}, | |
{false, false, false, true, false, false}, | |
}; | |
// Test cases | |
// 3 -> 5 = False | |
// 5 -> 3 = True | |
// 5 -> 1 = True | |
System.out.println(memberOfS(1, 5, r)); | |
} | |
// Test if (a, b) is a member of S. | |
private static boolean memberOfS(int a, int b, boolean[][] r) throws Exception { | |
boolean[] visited = new boolean[r.length]; | |
return search(r, visited, a, b); | |
} | |
// Helper argmax function | |
private static int argmax(boolean[] arr) throws Exception { | |
if (arr.length < 0) { | |
throw new Exception("Empty array passed to argmax"); | |
} | |
// Find the true value and return it's index | |
for (int i = 0; i < arr.length; i++) { | |
if (arr[i]) { | |
return i; | |
} | |
} | |
throw new Exception("No true found in array"); | |
} | |
// Takes the boolean array, starting and ending people. | |
// Returns whether there is a path between a and b. | |
private static boolean search(boolean[][] arr, boolean[] visited, int a, int b) throws Exception { | |
// Mark person as visited | |
visited[a] = true; | |
// Use argmax function to find next person | |
int next = argmax(arr[a]); | |
// If we have already visited the next person | |
// then we are in a loop and should return false. | |
if (visited[next]) { | |
return false; | |
// If we found the target then return true. | |
} else if (next == b) { | |
return true; | |
} | |
// Call search recursively | |
return search(arr, visited, next, b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment