Advertisement
Guest User

Pribic-Kickstart 2021 A - Problem C

a guest
Mar 21st, 2021
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. package kickstart.Y2021.round1A.RabbitHouse;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Queue;
  5. import java.util.Scanner;
  6.  
  7. /**
  8.  * @author pribic (Priyank Doshi)
  9.  * @since 21/03/21
  10.  */
  11. public class Solution {
  12.  
  13.   static int cost = 0;
  14.  
  15.   public static void main(String[] args) {
  16.     try (Scanner sc = new Scanner(System.in)) {
  17.       int T = sc.nextInt();
  18.       for (int tt = 1; tt <= T; tt++) {
  19.         cost = 0;
  20.         System.out.print("Case #" + tt + ": ");
  21.         int r = sc.nextInt();
  22.         int c = sc.nextInt();
  23.         int[][] grid = new int[r][c];
  24.         int max = Integer.MIN_VALUE;
  25.         for (int i = 0; i < r; i++) {
  26.           for (int j = 0; j < c; j++) {
  27.             grid[i][j] = sc.nextInt();
  28.             max = Math.max(max, grid[i][j]);
  29.           }
  30.         }
  31.         boolean[][] visited = new boolean[r][c];
  32.         ArrayDeque<Integer> queue = new ArrayDeque<>();
  33.         for (int i = 0; i < r; i++) {
  34.           for (int j = 0; j < c; j++) {
  35.             if (max == grid[i][j]) {
  36.               queue.addLast(i);
  37.               queue.addLast(j);
  38.             }
  39.           }
  40.         }
  41.         queue.addLast(-1);
  42.         int[] dx = new int[]{-1, 0, 1, 0};
  43.         int[] dy = new int[]{0, 1, 0, -1};
  44.         while (queue.size() > 1) {
  45.           if(queue.peek() == -1) {
  46.             max--;
  47.             queue.addLast(-1);
  48.             queue.removeFirst();
  49.           }
  50.           int x = queue.removeFirst();
  51.           int y = queue.removeFirst();
  52.           for (int i = 0; i < dx.length; i++) {
  53.             int tx = x + dx[i];
  54.             int ty = y + dy[i];
  55.             if(isValid(r, c, tx, ty) && !visited[tx][ty]) {
  56.               visited[tx][ty] = true;
  57.               if(grid[tx][ty] < max - 1) {
  58.                 cost += max - 1 - grid[tx][ty];
  59.                 grid[tx][ty] = max - 1;
  60.               }
  61.               queue.addLast(tx);
  62.               queue.addLast(ty);
  63.             }
  64.           }
  65.         }
  66.         System.out.println(cost);
  67.       }
  68.     }
  69.   }
  70.  
  71.   private static boolean isValid(int r, int c, int i, int j) {
  72.     return i >= 0 && j >= 0 && i < r & j < c;
  73.   }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement