diff --git a/src/Search.java b/src/Search.java index cebb278..6343fa5 100644 --- a/src/Search.java +++ b/src/Search.java @@ -1,3 +1,8 @@ +import java.util.List; +import java.util.ArrayList; +import java.util.Queue; +import java.util.LinkedList; + public class Search { /** * Finds the location of the nearest reachable cheese from the rat's position. @@ -29,6 +34,105 @@ 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 = ratLocation(maze); + + // queue = [] + Queue queue = new LinkedList<>(); + // qeueu.add(start); + queue.add(start); + + // while queue != empty + while (!queue.isEmpty()) { + // current = queue.pop + int[] current = queue.poll(); + // if visited: continue + int curR = current[0]; + int curC = current[1]; + + // if visited : continue + if (visited[curR][curC]) { + continue; + } + + // mark visited + visited[curR][curC] = true; + // if current is cheese: return current + if (maze[curR][curC] == 'c') { + return current; + } + + queue.addAll(getNeighbors(maze, current)); + } + + // return hungee + throw new HungryRatException(); + + } + + + + public static List getNeighbors (char[][] maze, int[] current) { + int currR = current[0]; + int currC = current[1]; + + // UP [-1, 0] + // DOWN [1,0] + // left [0, -1] + // right [0,1] + + int[][] directions = { + {-1,0}, // up + {1,0}, // down4 + {0,-1}, // left + {0,1} // right + }; + + List possibleMoves = new ArrayList<>(); + + for (int[] direction : directions) { + int changeR = direction[0]; + int changeC = direction[1]; + + int newR = currR + changeR; + int newC = currC + changeC; + + if (newR >= 0 && newR < maze.length && + newC >= 0 && newC < maze[newR].length + && maze[newR][newC] != 'w') { + // valid move! + int[] validMove = {newR, newC}; + possibleMoves.add(validMove); + } + + } + return possibleMoves; + } + + public static int[] ratLocation(char[][] maze) throws EscapedRatException, CrowdedMazeException { + int[] location = null; + + // Searching + 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) { + // 404 rat not found + throw new EscapedRatException(); + } + return location; + } + + public static void main(String[] args) { + } } \ No newline at end of file