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
76 changes: 73 additions & 3 deletions src/SalamanderSearch.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import java.util.ArrayList;
import java.util.List;
import java.util.*;

public class SalamanderSearch {
public static void main(String[] args) {
Expand Down Expand Up @@ -43,6 +42,77 @@ public static void main(String[] args) {
* @return whether the salamander can reach the food
*/
public static boolean canReach(char[][] enclosure) {
return false;
int[] start = salamanderLocation(enclosure);
boolean[][] visited = new boolean[enclosure.length][enclosure[0].length];


return canReach(enclosure, start, visited);
}

public static boolean canReach(char[][] enclosure, int[] currentLocation, boolean[][] visited){
int curR = currentLocation[0];
int curC = currentLocation[1];

if(visited[curR][curC]) return false;
if(enclosure[curR][curC] == 'f')return true;

visited[curR][curC] = true;

List<int[]> moves = possibleMoves(enclosure, currentLocation);
for(int[] move : moves){
if(canReach(enclosure, move, visited)) return true;


}
return false;
}

// returns an array that holds a {row, column} --> {3, 4}
public static int[] salamanderLocation(char[][] enclosure){
for(int r = 0; r < enclosure.length; r++){
for(int c = 0; c < enclosure[0].length; c++){
if(enclosure[r][c] == 's') return new int[]{r,c};
}
}
throw new IllegalArgumentException("No salamander present");
}

public static List<int[]> possibleMoves(char[][] enclosure, int[] currentLocation){
int curR = currentLocation[0];
int curC = currentLocation[1];

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

// UP
int newR = curR -1;
int newC = curC;
if(newR >= 0 && enclosure[newR][newC] != 'W'){
moves.add(new int[]{newR, newC});
}

//DOWN
newR = curR + 1;
newC = curC;
if(newR < enclosure.length && enclosure[newR][newC] != 'W'){
moves.add(new int[]{newR, newC});
}

//Left
newR = curR;
newC = curC - 1;
if(newC >= 0 && enclosure[newR][newC] != 'W'){
moves.add(new int[]{newR, newC});
}

//RIGHT
newR = curR;
newC = curC + 1;
if(newC < enclosure[0].length && enclosure[newR][newC] != 'W'){
moves.add(new int[]{newR, newC});
}

return moves;
}


}
Loading