Guest User

easy

a guest
Jun 17th, 2021
421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. import java.util.*;
  2. public class b {
  3.  
  4. static int [][] dirs = {{0,1},{1,0},{-1,0},{0,-1}};
  5.  
  6. public static int maxTrees(int [][] matrix, int [][] fireStations, int [][] fires) {
  7.  
  8. // [x, y]
  9. Queue<int[]> fireQ = new LinkedList<>();
  10. Queue<int[]> fireStationQ = new LinkedList<>();
  11.  
  12. int N = matrix.length, M = matrix[0].length;
  13.  
  14. boolean [][] visitedFire = new boolean [N][M];
  15. boolean [][] visitedStation = new boolean [N][M];
  16.  
  17. int savedTrees = 0;
  18. for (int [] fireStation: fireStations) {
  19. int x = fireStation[0], y = fireStation[1];
  20. if (matrix[x][y] == -1) continue;
  21. savedTrees += matrix[x][y];
  22. visitedStation[x][y] = true;
  23. fireStationQ.add(fireStation);
  24. }
  25.  
  26. for (int [] fire: fires) {
  27. matrix[fire[0]][fire[1]] = 0;
  28. visitedFire[fire[0]][fire[1]] = true;
  29. fireQ.add(fire);
  30. }
  31.  
  32.  
  33. while (!fireStationQ.isEmpty()) {
  34.  
  35. int stations = fireStationQ.size();
  36.  
  37. //stations have priority, process before fire step
  38. for (int i =0; i < stations;i++){
  39. int [] station = fireStationQ.poll();
  40.  
  41. for (int [] dir : dirs) {
  42. int x = station[0]+dir[0];
  43. int y = station[1]+dir[1];
  44.  
  45. if (x >=0 && y >=0 && x < N && y <M && matrix[x][y] != -1 && !visitedStation[x][y]) {
  46. visitedStation[x][y] = true;
  47. savedTrees += matrix[x][y];
  48. fireStationQ.add(new int [] { x,y});
  49. }
  50. }
  51. }
  52.  
  53. // assume fires can still spread after meeting firefighter
  54. int fireSize = fireQ.size();
  55. for (int i = 0; i < fireSize; i++){
  56. int [] fireCell = fireQ.poll();
  57. for (int [] dir : dirs) {
  58. int x = fireCell[0]+dir[0];
  59. int y = fireCell[1]+dir[1];
  60. if (x >=0 && y >=0 && x < N && y < M && matrix[x][y] != -1 && !visitedFire[x][y]) {
  61. visitedFire[x][y] = true;
  62. matrix[x][y] = 0;
  63. fireQ.add(new int [] { x,y});
  64. }
  65. }
  66. }
  67. }
  68.  
  69. return savedTrees;
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment