File tree Expand file tree Collapse file tree
main/kotlin/com/devstromo/medium/p2101
test/kotlin/com/devstromo/medium/p2101 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package com.devstromo.medium.p2101
22
3+ import kotlin.math.pow
4+
35class SolutionKt {
46 fun maximumDetonation (bombs : Array <IntArray >): Int {
57 val n = bombs.size
@@ -31,6 +33,42 @@ class SolutionKt {
3133 return max
3234 }
3335
36+ fun maximumDetonationBest (bombs : Array <IntArray >): Int {
37+ val graph = Array (bombs.size) { arrayListOf<Int >() }.apply {
38+ for (i in 0 .. < bombs.size - 1 ) {
39+ val (xi, yi, ri) = bombs[i]
40+
41+ for (j in i + 1 .. < bombs.size) {
42+ val (xj, yj, rj) = bombs[j]
43+
44+ if ((xj - xi).toDouble().pow(2.0 ) + (yj - yi).toDouble().pow(2.0 ) <= ri.toDouble()
45+ .pow(2.0 )
46+ ) get(i).add(j)
47+ if ((xi - xj).toDouble().pow(2.0 ) + (yi - yj).toDouble().pow(2.0 ) <= rj.toDouble()
48+ .pow(2.0 )
49+ ) get(j).add(i)
50+ }
51+ }
52+ }
53+ var maxD = 0
54+ for (i in bombs.indices) {
55+ maxD = maxOf(maxD, dfs(i, graph, BooleanArray (bombs.size)))
56+ if (maxD == bombs.size) break
57+ }
58+ return maxD
59+ }
60+
61+ fun dfs (bomb : Int , graph : Array <ArrayList <Int >>, exploded : BooleanArray ): Int {
62+ if (exploded[bomb]) return 0
63+
64+ exploded[bomb] = true
65+ var explosions = 1
66+
67+ for (b in graph[bomb]) explosions + = dfs(b, graph, exploded)
68+
69+ return explosions
70+ }
71+
3472 private fun dfs (current : Int , graph : Array <MutableList <Int >>, visited : BooleanArray ): Int {
3573 visited[current] = true
3674 var count = 1
Original file line number Diff line number Diff line change @@ -46,4 +46,45 @@ class SolutionKtUnitTest {
4646 )
4747 )
4848 }
49+
50+ @Test
51+ fun `Test Detonate the Maximum Bombs Best` () {
52+ assertEquals(
53+ 2 , solution.maximumDetonationBest(
54+ arrayOf(
55+ intArrayOf(2 , 1 , 3 ),
56+ intArrayOf(6 , 1 , 4 ),
57+ )
58+ )
59+ )
60+ assertEquals(
61+ 1 , solution.maximumDetonationBest(
62+ arrayOf(
63+ intArrayOf(1 , 1 , 5 ),
64+ intArrayOf(10 , 10 , 5 ),
65+ )
66+ )
67+ )
68+ assertEquals(
69+ 5 , solution.maximumDetonationBest(
70+ arrayOf(
71+ intArrayOf(1 , 2 , 3 ),
72+ intArrayOf(2 , 3 , 1 ),
73+ intArrayOf(3 , 4 , 2 ),
74+ intArrayOf(4 , 5 , 3 ),
75+ intArrayOf(5 , 6 , 4 )
76+ )
77+ )
78+ )
79+
80+ assertEquals(
81+ 1 ,
82+ solution.maximumDetonationBest(
83+ arrayOf(
84+ intArrayOf(1 , 1 , 100000 ),
85+ intArrayOf(100000 , 100000 , 1 )
86+ )
87+ )
88+ )
89+ }
4990}
You can’t perform that action at this time.
0 commit comments