Advertisement
saurav_kalsoor

House Renovation - KOTLIN

May 19th, 2022
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Author - Saurav Kalsoor
  2. //House Renovation - KOTLIN
  3.  
  4. import java.util.*
  5. import java.lang.*
  6.  
  7. var sc: Scanner = Scanner(System.`in`)
  8. var area = 0
  9.  
  10. fun main() {
  11.     val n: Int = sc.nextInt()
  12.     val m: Int = sc.nextInt()
  13.     val q: Int = sc.nextInt()
  14.     val a = Array(n) { IntArray(m) }
  15.     for (i in 0 until n) {
  16.         for (j in 0 until m) {
  17.             a[i][j] = sc.nextInt()
  18.         }
  19.     }
  20.     val queries = IntArray(q)
  21.     for (i in queries.indices) {
  22.         queries[i] = sc.nextInt()
  23.     }
  24.     val result = houseRenovation(n, m, q, a, queries)
  25.     for (i in result.indices) {
  26.         print(result[i].toString() + " ")
  27.     }
  28.     println()
  29. }
  30.  
  31. fun dfs(a: Array<IntArray>, i: Int, j: Int, visited: Array<BooleanArray>) {
  32.     if (visited[i][j]) return
  33.     visited[i][j] = true
  34.     area++
  35.     if (a[i][j] and 1 == 0) {
  36.         dfs(a, i, j - 1, visited)
  37.     }
  38.     if (a[i][j] and 2 == 0) {
  39.         dfs(a, i + 1, j, visited)
  40.     }
  41.     if (a[i][j] and 4 == 0) {
  42.         dfs(a, i, j + 1, visited)
  43.     }
  44.     if (a[i][j] and 8 == 0) {
  45.         dfs(a, i - 1, j, visited)
  46.     }
  47. }
  48.  
  49. fun houseRenovation(n: Int, m: Int, q: Int, a: Array<IntArray>, queries: IntArray): IntArray {
  50.     val visited = Array(n){BooleanArray(m)}
  51.     // val a = Array(n) { IntArray(m) }
  52.     for (i in 0 until n) {
  53.         for (j in 0 until m) {
  54.             visited[i][j] = false
  55.         }
  56.     }
  57.     val hm: MutableMap<Int, Int> = HashMap<Int, Int>()
  58.     for (i in 0 until n) {
  59.         for (j in 0 until m) {
  60.             if (visited[i][j] == false) {
  61.                 area = 0
  62.                 dfs(a, i, j, visited)
  63.                 hm.put(area, hm.getOrDefault(area, 0) + 1)
  64.             }
  65.         }
  66.     }
  67.     val result = IntArray(q)
  68.     for (i in queries.indices) {
  69.         if (hm.containsKey(queries[i])) {
  70.             result[i] = hm[queries[i]]!!
  71.         } else {
  72.             result[i] = 0
  73.         }
  74.     }
  75.     return result
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement