diff --git a/src/SalamanderSearch.java b/src/SalamanderSearch.java index 93c9ab5..4f2f577 100644 --- a/src/SalamanderSearch.java +++ b/src/SalamanderSearch.java @@ -43,7 +43,71 @@ public static void main(String[] args) { * @return whether the salamander can reach the food * @throws IllegalArgumentException if the enclosure does not contain a salamander */ - public static boolean canReach(char[][] enclosure) { + public static boolean canReach(char[][] enclosure) throws IllegalArgumentException { + 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[] current, boolean[][] visited) { + int curR = current[0]; + int curC = current[1]; + + if (enclosure[curR][curC] == 'f') return true; + if (visited[curR][curC]) return false; + + visited[curR][curC] = true; + + List neighbors = possibleMoves(enclosure, current); + + for (int[] neighbor : neighbors) if (canReach(enclosure, neighbor, visited)) return true; return false; } + + // O(n*m) n = # of rows, m = # of cols + 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"); + } + + public static List possibleMoves(char[][] enclosure, int[] current) { + List moves = new ArrayList<>(); + + int curR = current[0]; + int curC = current[1]; + + // 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[newR].length && enclosure[newR][newC] != 'W') { + moves.add(new int[] {newR, newC}); + } + + return moves; + } }