diff --git a/src/Fire.java b/src/Fire.java index b968c51..4eeee8a 100644 --- a/src/Fire.java +++ b/src/Fire.java @@ -1,3 +1,8 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + public class Fire { /** * Returns how long it takes for all vulnerable trees to be set on fire if a @@ -38,6 +43,66 @@ public class Fire { public static int timeToBurn(char[][] forest, int matchR, int matchC) { // HINT: when adding to your BFS queue, you can include more information than // just a location. What other information might be useful? - return -1; + if (forest[matchR][matchC] != 't') { + return 0; + } + + + int[] start = new int[]{matchR, matchC, 0}; + boolean[][] burnt = new boolean[forest.length][forest[0].length]; + + Queue queue = new LinkedList<>(); + queue.add(start); + + int maxTime = 0; + + while(!queue.isEmpty()){ + int[] current = queue.poll(); + + int row = current[0]; + int col = current[1]; + int time = current[2]; + + // if the current tree is down continue + if (burnt[row][col]){ + continue; + } + + burnt[row][col] = true; + + List moves = possibleMoves(forest, row, col); + + // add reachable tree to the queue + for (var move : moves){ + int[] toAdd = new int[]{move[0],move[1], time + 1}; + queue.add(toAdd); + } + + if( time > maxTime){ + maxTime = time; + } + } + return maxTime; + } + + public static List possibleMoves(char[][] forest, int row, int col) { + List moves = new ArrayList<>(); + int[][] directions = { + {-1, 0}, // up + { 1, 0}, // down + { 0,-1}, // left + { 0, 1} // right + }; + + for (int[] d : directions) { + int nr = row + d[0], nc = col + d[1]; + if (nr >= 0 && nr < forest.length && + nc >= 0 && nc < forest[0].length && + forest[nr][nc] == 't') { + moves.add(new int[]{nr, nc}); + } + } + + return moves; } } \ No newline at end of file