Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 86 additions & 1 deletion src/ExplorerSearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,91 @@ public static int reachableArea(int[][] island) {
// Implement your method here!
// Please also make more test cases
// I STRONGLY RECOMMEND testing some helpers you might make too
return -1;
int[] start = explorerLocation(island);
boolean[][] visited = new boolean[island.length][island[0].length];
return reachableArea(island, start, visited);
}

public static int reachableArea(int[][] island, int[] current, boolean[][] visited) {
int curR = current[0];
int curC = current[1];

// if we've been here before, return 0
if (visited[curR][curC]) return 0;

// if we haven't, count the current space and set visited to true
int spaces = 1;
visited[curR][curC] = true;

// find the list of where we can get to from here
List<int[]> neighbors = possibleMoves(island, current);

// go through the list
for (int[] neighbor : neighbors) {
//add the results to our number of valid spaces
spaces += reachableArea(island, neighbor, visited);
}

// send the list back to top
// after we run out of valid spaces, this should return the final result to the top level
return spaces;
}

public static int[] explorerLocation(int[][] island) {
//go through the area and find the explorer
for (int r=0; r < island.length; r++) {
for (int c = 0; c < island[r].length; c++) {
if (island[r][c] == 0) {
int[] location = new int[] {r, c};
return location;
}
}
}

// you didn't give explicit instructions for a missing explorer so I am doing it the same as on the live code assignment

// if this was an undesirable result, a missing explorer could also set the start location out of bounds {-1, -1} with a check that returns 0 total moves for that starting location (if there's no explorer on the island, 0 "squares" are explorable)
throw new IllegalArgumentException("No explorer on the island.");
}

public static List<int[]> possibleMoves(int[][] island, int[] current) {
List<int[]> moves = new ArrayList<>();

int curR = current[0];
int curC = current[1];


// up
int newR = curR - 1;
int newC = curC;

if (newR >= 0 && island[newR][newC] == 1) {
moves.add(new int[]{newR, newC});
}

// down
newR = curR + 1;
newC = curC;

if (newR < island.length && island[newR][newC] == 1) {
moves.add(new int[]{newR, newC});
}
// left
newR = curR;
newC = curC - 1;

if (newC >= 0 && island[newR][newC] == 1) {
moves.add(new int[] {newR, newC});
}

// right
newR = curR;
newC = curC + 1;

if (newC < island[newR].length && island[newR][newC] == 1) {
moves.add(new int[] {newR, newC});
}

return moves;
}
}
Loading