dfs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
fun dfs(graph:MutableList<MutableList<Int>>,v:Int, visited:MutableList<Boolean>){
visited[v] = true
print("$v ")
for(i in graph[v]){
if(!(visited[i])){
dfs(graph, i ,visited)
}
}
}
fun main(){
// mutableListOf<Int>()는 빈 리스트를 생성하기 때문에 제너릭을 써야함
val graph = mutableListOf(
mutableListOf<Int>(),
mutableListOf(2,3,8),
mutableListOf(1,7),
mutableListOf(1,4,5),
mutableListOf(3,5),
mutableListOf(3,4),
mutableListOf(7),
mutableListOf(2,6,8),
mutableListOf(1,7),
)
val visited = MutableList(9,{false})
dfs(graph, 1, visited) //1 2 7 6 8 3 4 5
}
|
cs |
BFS도 DFS와 같은 그래프를 사용합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import java.util.*
fun bfs(graph:MutableList<MutableList<Int>>,v:Int, visited:MutableList<Boolean>){
var q : Queue<Int> = LinkedList<Int>()
q.add(v)
visited[v] = true
while(!q.isEmpty()){
var a = q.poll()
print("$a ")
for(i in graph[a]){
if(!visited[i]){
q.add(i)
visited[i]=true
}
}
}
}
fun main(){
// mutableListOf<Int>()는 빈 리스트를 생성하기 때문에 제너릭을 써야함
val graph = mutableListOf(
mutableListOf<Int>(),
mutableListOf(2,3,8),
mutableListOf(1,7),
mutableListOf(1,4,5),
mutableListOf(3,5),
mutableListOf(3,4),
mutableListOf(7),
mutableListOf(2,6,8),
mutableListOf(1,7),
)
val visited = MutableList(9,{false})
bfs(graph, 1, visited) //1 2 3 8 7 4 5 6
}
|
cs |
'알고리즘 공부 > bfs,dfs' 카테고리의 다른 글
백준 11724 with Kotlin (0) | 2021.08.06 |
---|---|
백준2606번 with Kotlin (0) | 2021.08.05 |
백준 1260번 with 코틀린 (0) | 2021.07.23 |
이코테 bfs #data class #굉장히 중요 (0) | 2021.07.14 |
이코테 문제 #dfs # 001을 =[0,0,1]의 list로 만드는 방법 (0) | 2021.07.14 |