Skip to content
Open
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
81 changes: 81 additions & 0 deletions src/SalamanderSearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,87 @@ public static void main(String[] args) {
* @return whether the salamander can reach the food
*/
public static boolean canReach(char[][] enclosure) {
// find salamander
int[] start = salamanderLocation(enclosure);
// this boolean is the same size as the enclosure and starts off all false by default
boolean[][] visited = new boolean[enclosure.length][enclosure[0].length];

// recursive dfs
return canReach(enclosure, start, visited);
}

/* Helper method that passes in current location and boolean record of visited locations. */
public static boolean canReach(char[][] enclosure, int[] current, boolean[][] visited) {
int currRow = current[0];
int currCol = current[1];

if (visited[currRow][currCol]) return false;
if (enclosure[currRow][currCol] == 'f') return true;

visited[currRow][currCol] = true;

List<int[]> moves = possibleMoves(enclosure, current);

for (var move: moves) {
if (canReach(enclosure, move, visited)) return true;
}

return false;
}


/* Helper method to find salamander starting position.
Returns an array of integers that represent the row and column of the starting position of the salamander */
public static int[] salamanderLocation(char[][] enclosure) {
for (int r = 0; r < enclosure.length; r++) {
for (int c = 0; c < enclosure[r].length; c++) {
if (enclosure[r][c] == 's') {
return new int[]{r, c};
}
}
}
throw new IllegalArgumentException("No salamander present");
}

/* Helper method
* Given a current location, what are the possible valid moves
* Checks up, down, left, right
*/
public static List<int[]> possibleMoves(char[][] enclosure, int[] currentLocation) {
int currentRow = currentLocation[0];
int currentCol = currentLocation[1];

List<int[]> moves = new ArrayList<>();

// UP
int newRow = currentRow - 1;
int newCol = currentCol;
if (newRow >= 0 && enclosure[newRow][newCol] != 'W') {
moves.add(new int[]{newRow, newCol});
}

// DOWN
newRow = currentRow + 1;
newCol = currentCol;
if (newRow < enclosure.length && enclosure[newRow][newCol] != 'W') {
moves.add(new int[]{newRow, newCol});
}

// LEFT
newRow = currentRow;
newCol = currentCol - 1;
if (newCol >= 0 && enclosure[newRow][newCol] != 'W') {
moves.add(new int[]{newRow, newCol});
}

// RIGHT
newRow = currentRow;
newCol = currentCol + 1;
if (newCol < enclosure[0].length && enclosure[newRow][newCol] != 'W') {
moves.add(new int[]{newRow, newCol});
}

return moves;
}

}