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
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"java.debug.settings.onBuildFailureProceed": true
}
82 changes: 82 additions & 0 deletions src/SalamanderSearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,88 @@ public static void main(String[] args) {
* @throws IllegalArgumentException if the enclosure does not contain a salamander
*/
public static boolean canReach(char[][] enclosure) {
int[] start = salamanderLocation(enclosure);
boolean[][] visited = new boolean[enclosure.length][enclosure[0].length];
return canReach(enclosure, start, visited);
}

//questions:
//
//
public static boolean canReach(char[][] enclosure, int[] current, boolean[][] visited)
{
int curR = current[0];
int curC = current[1];
if(enclosure[curR][curC] == 'f') return true; //if the food is found

if(visited[curR][curC]) return false; //if we've already seen that location

visited[curR][curC] = true;

List<int[]> neighbors = possibleMoves(enclosure, current); //getting the possible places you can move using recursion
for(int[] neighbor : neighbors)
{
if(canReach(enclosure, neighbor, visited)) return true; //??
}
return false;
}

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

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

//UP
int newRow = curR-1;
int newCol = curC;

if(newRow >= 0 && enclosure[newRow][newCol] != 'W')
{
moves.add(new int[]{newRow,newCol});
}
//DOWN
newRow = curR+1;
newCol = curC;

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

//RIGHT
newRow = curR;
newCol = curC+1;
if(newCol < enclosure[newRow].length && enclosure[newRow][newCol] != 'W')
{
moves.add(new int[]{newRow,newCol});
}
return moves;
}
//O(n*m):
//n = # of cols
//m = # of rows
public static int[] salamanderLocation(char[][] enclosure)
{
for(int row = 0; row < enclosure.length; row++)
{
for(int col = 0; col < enclosure[0].length; col++)
{
if(enclosure[row][col] == 's')
{
int[] location = new int[] {row,col};
return location;
}
}
}
throw new IllegalArgumentException("No salamander present");
}
}
Loading