diff --git a/src/Fire.java b/src/Fire.java index b968c51..e3a4b4e 100644 --- a/src/Fire.java +++ b/src/Fire.java @@ -1,3 +1,6 @@ +import java.util.LinkedList; +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 +41,54 @@ 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; + + + + int rows = forest.length; + int cols = forest[0].length; + + boolean[][] visited = new boolean[rows][cols]; + + // Check that starting point is a tree + if (forest[matchR][matchC] != 't') { + return -1; + } + + int[][] directions = { + {-1, 0}, // up + {1, 0}, // down + {0, -1}, // left + {0, 1} // right + }; + + Queue queue = new LinkedList<>(); + queue.add(new int[]{matchR, matchC, 0}); + visited[matchR][matchC] = true; + + int maxTime = 0; + + while (!queue.isEmpty()) { + int[] current = queue.poll(); + int r = current[0]; + int c = current[1]; + int time = current[2]; + + maxTime = Math.max(maxTime, time); + + for (int[] dir : directions) { + int newR = r + dir[0]; + int newC = c + dir[1]; + + if (newR >= 0 && newR < rows && newC >= 0 && newC < cols + && !visited[newR][newC] + && forest[newR][newC] == 't') { + + visited[newR][newC] = true; + queue.add(new int[]{newR, newC, time + 1}); + } + } + } + + return maxTime; } } \ No newline at end of file diff --git a/src/FireTest.java b/src/FireTest.java index b3b9085..2ed215d 100644 --- a/src/FireTest.java +++ b/src/FireTest.java @@ -20,4 +20,58 @@ public void testTimeToBurnExample() { assertEquals(expected, actual); } + + @Test + public void testSingleTree() { + char[][] forest = { + {'t'} + }; + assertEquals(0, Fire.timeToBurn(forest, 0, 0)); + } + + @Test + public void testSingleEmptySpace() { + char[][] forest = { + {'.'} + }; + assertEquals(-1, Fire.timeToBurn(forest, 0, 0)); + } + + @Test + public void testDisconnectedTrees() { + char[][] forest = { + {'t', '.', 't'}, + {'.', '.', '.'}, + {'t', '.', 't'} + }; + assertEquals(0, Fire.timeToBurn(forest, 0, 0)); + } + + @Test + public void testFullBlockOfTrees() { + char[][] forest = { + {'t', 't'}, + {'t', 't'} + }; + assertEquals(2, Fire.timeToBurn(forest, 0, 0)); + } + + @Test + public void testFireStartsOnGround() { + char[][] forest = { + {'t', 't'}, + {'.', 't'} + }; + assertEquals(-1, Fire.timeToBurn(forest, 1, 0)); + } + + @Test + public void testEdgeSpread() { + char[][] forest = { + {'t', 't', 't', '.', '.'}, + {'.', '.', 't', '.', '.'}, + {'.', '.', 't', 't', 't'} + }; + assertEquals(6, Fire.timeToBurn(forest, 0, 0)); + } }