diff --git a/src/Search.java b/src/Search.java index cebb278..4ade538 100644 --- a/src/Search.java +++ b/src/Search.java @@ -1,3 +1,9 @@ +import java.util.List; +import java.util.Queue; +import java.util.ArrayList; +import java.util.LinkedList; + + public class Search { /** * Finds the location of the nearest reachable cheese from the rat's position. @@ -18,7 +24,7 @@ public class Search { * woowwcwo * ooooRwoo * oowwwooo - * oooocooo + * oooocooo * * The method will return [0,4] as the nearest cheese. * @@ -29,6 +35,67 @@ public class Search { * @throws HungryRatException if there is no reachable cheese */ public static int[] nearestCheese(char[][] maze) throws EscapedRatException, CrowdedMazeException, HungryRatException { - return null; + boolean[][] visited = new boolean[maze.length][maze[0].length]; + int[] start = ratDetector(maze); + Queue queue = new LinkedList<>(); + queue.add(start); + + while(!queue.isEmpty()){ + int[] current = queue.poll(); + int curR = current[0]; + int curC = current[1]; + + if(visited[curR][curC]) continue; + visited[curR][curC] = true; + if(maze[curR][curC] == 'c') return current; + + queue.addAll(getNeighbors(maze, current)); + } + throw new HungryRatException(); + } + + public static List getNeighbors(char[][] maze, int[] current){ + int curR = current[0]; + int curC = current[1]; + List validMoves = new ArrayList<>(); + + int [][] directions = { + {-1, 0}, // up + {1, 0}, // down + {0, -1}, // left + {0, 1} // right + }; + + for(int[] direction : directions){ + int changeR = direction[0]; + int changeC = direction[1]; + + int newR = curR + changeR; + int newC = curC + changeC; + if (newR >= 0 && newR < maze.length && + newC >= 0 && newC < maze[newR].length && + maze[newR][newC] != 'w'){ + int[] validMove = {newR, newC}; + validMoves.add(validMove); + } + } + return validMoves; + } + + public static int[] ratDetector(char[][] maze) throws EscapedRatException, CrowdedMazeException, HungryRatException { + int[] location = null; + + for(int r = 0; r < maze.length; r++){ + for(int c = 0; c < maze[r].length; c++){ + if(maze[r][c] == 'R'){ + if(location != null){ + throw new CrowdedMazeException(); + } + } + location = new int[]{r,c}; + } + } + if(location == null) throw new EscapedRatException(); + return location; } } \ No newline at end of file