Skip to content

Commit b568b55

Browse files
committed
[hackerrank] "DFS: Connected Cell in a Grid" 추가
1 parent a4ddd9a commit b568b55

File tree

2 files changed

+136
-0
lines changed

2 files changed

+136
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package hackerrank.graphs
2+
3+
import kotlin.math.max
4+
5+
fun maxRegion(grid: Array<Array<Int>>): Int {
6+
7+
var result = 0
8+
val visited = Array(grid.size) {
9+
Array(grid.first().size) {
10+
false
11+
}
12+
}
13+
14+
grid.indices.forEach { row ->
15+
grid.first().indices.forEach inner@{ col ->
16+
if (visited[row][col]) return@inner
17+
18+
val size = calculateRegion(
19+
grid,
20+
visited,
21+
row,
22+
col
23+
)
24+
25+
result = max(result, size)
26+
}
27+
}
28+
29+
return result
30+
}
31+
32+
fun calculateRegion(
33+
grid: Array<Array<Int>>,
34+
visited: Array<Array<Boolean>>,
35+
row: Int,
36+
col: Int
37+
): Int {
38+
39+
if (0 > row || row >= grid.size) return 0
40+
if (0 > col || col >= grid.first().size) return 0
41+
if (grid[row][col] == 0) return 0
42+
if (visited[row][col]) return 0
43+
44+
visited[row][col] = true
45+
var count = 1
46+
47+
(row - 1..row + 1).forEach { r ->
48+
(col - 1..col + 1).forEach { c ->
49+
count += calculateRegion(grid, visited, r, c)
50+
}
51+
}
52+
53+
return count
54+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package hackerrank.graphs
2+
3+
import org.junit.Assert.assertEquals
4+
import org.junit.Test
5+
6+
class DFSConnectedCellInAGridKtTest {
7+
8+
@Test
9+
fun `maxRegion sample test case 0`() {
10+
11+
// given
12+
val input = arrayOf(
13+
arrayOf(1, 1, 0, 0),
14+
arrayOf(0, 1, 1, 0),
15+
arrayOf(0, 0, 1, 0),
16+
arrayOf(1, 0, 0, 0)
17+
)
18+
19+
// when
20+
val result = maxRegion(input)
21+
22+
// then
23+
assertEquals(5, result)
24+
}
25+
26+
@Test
27+
fun `maxRegion sample test case 1`() {
28+
29+
// given
30+
val input = arrayOf(
31+
arrayOf(0, 0, 1, 1),
32+
arrayOf(0, 0, 1, 0),
33+
arrayOf(0, 1, 1, 0),
34+
arrayOf(0, 1, 0, 0),
35+
arrayOf(1, 1, 0, 0)
36+
)
37+
38+
// when
39+
val result = maxRegion(input)
40+
41+
// then
42+
assertEquals(8, result)
43+
}
44+
45+
@Test
46+
fun `maxRegion sample test case 2`() {
47+
48+
// given
49+
val input = arrayOf(
50+
arrayOf(1, 0, 1, 1, 0),
51+
arrayOf(1, 1, 0, 0, 1),
52+
arrayOf(0, 1, 1, 1, 0),
53+
arrayOf(0, 0, 0, 0, 1),
54+
arrayOf(1, 1, 1, 0, 0)
55+
)
56+
57+
// when
58+
val result = maxRegion(input)
59+
60+
// then
61+
assertEquals(10, result)
62+
}
63+
64+
@Test
65+
fun `maxRegion 대각선도 고려해야 한다`() {
66+
67+
// given
68+
val input = arrayOf(
69+
arrayOf(1, 1, 0, 0),
70+
arrayOf(0, 1, 1, 0),
71+
arrayOf(0, 0, 1, 0),
72+
arrayOf(1, 0, 0, 1)
73+
)
74+
75+
// when
76+
val result = maxRegion(input)
77+
78+
// then
79+
assertEquals(6, result)
80+
}
81+
82+
}

0 commit comments

Comments
 (0)