diff --git a/src/SalamanderSearch.java b/src/SalamanderSearch.java index 688cda7..9155c1c 100644 --- a/src/SalamanderSearch.java +++ b/src/SalamanderSearch.java @@ -43,6 +43,72 @@ public static void main(String[] args) { * @return whether the salamander can reach the food */ public static boolean canReach(char[][] enclosure) { + 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(visited[curR][curC]) return false; + if(enclosure[curR][curC] == 'f') return true; + + visited[curR][curC] = true; + + List moves = possibleMoves(enclosure, current); + for(int[] move : moves) { + if(canReach(enclosure, move, visited)) return true; + } return false; } -} + + public static List possibleMoves(char[][] enclosure, int[] current) { + int curR = current[0]; + int curC = current[1]; + + List 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; + } + + 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"); + } +} \ No newline at end of file