From 1de78afd53a7ef9c551e7a5f7e16e49ee95b88fb Mon Sep 17 00:00:00 2001 From: VibeSyntax <138536097+beza102@users.noreply.github.com> Date: Tue, 3 Jun 2025 11:50:19 -0700 Subject: [PATCH] completed the livecode --- src/Search.java | 106 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 105 insertions(+), 1 deletion(-) diff --git a/src/Search.java b/src/Search.java index cebb278..c6b10dd 100644 --- a/src/Search.java +++ b/src/Search.java @@ -1,3 +1,9 @@ +import java.util.ArrayList; +import java.util.Currency; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + public class Search { /** * Finds the location of the nearest reachable cheese from the rat's position. @@ -29,6 +35,104 @@ 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<>(); + //queue.add(start) + + queue.add(start); + + //while queue not empty + while (!queue.isEmpty()) { + //current = queue.pop + int[] current = queue.poll(); + 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; + } + List neighbors = getNeighbors(maze, current); + //add all neighbors to queue + // for(int[] neighbor : getNeighbors(maze, current)){ + // } OR| + //add all neighbors to queue + queue.addAll(getNeighbors(maze, current)); + + + //throw hungee + throw new HungryRatException(); + } + + } + + + + public static List getNeighbors(char[][] maze, int[] current){ + int curR= current[0]; + int curC = current[1]; + + int [][] directions ={ + //up [-1, 0] + {-1, 0}, + //down[1, 0] + {1, 0}, + //left[0, -1] + {0, -1}, + //right [0, 1] + {0, 1} + }; + + List possibleMoves = new ArrayList<>(); + + 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'){ + //valid move + int[] validMove = {newR, newC}; + possibleMoves.add(validMove); + + } + } + return possibleMoves; + } + + public static int[] ratLocation(char[][] maze)throws EscapedRatException, CrowdedMazeException, HungryRatException { + int[] location = null; + //serching + for(int r=0; r