알고리즘 공부/bfs,dfs

이코테 문제 #dfs # 001을 =[0,0,1]의 list로 만드는 방법

_우지 2021. 7. 14. 20:14

//출처 https://www.youtube.com/watch?v=7C9RgOcvkvo&t=1605s

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
fun dfs(graph: MutableList<MutableList<Int>>, x:Int , y:Int, n:Int , m:Int): Boolean {
    if (x <= -1 || x >= n || y <= -1 || y >= m){
        return false
    }
    if(graph[x][y]==0){
        graph[x][y] = 1
        dfs(graph,x-1,y,n,m)
        dfs(graph,x,y-1,n,m)
        dfs(graph,x+1,y,n,m)
        dfs(graph,x,y+1,n,m)
        return true
    }
    return false
}
 
 
fun main(){
    //val beforeTime = System.currentTimeMillis() //코드 실행 전에 시간 받아오기
 
 
    // 001을 =[0,0,1]의 list로 만드는 방법
    // readLine()!!.map{it.toInt()-48}.toMutableList(
    // 아니 그냥 map만 해도 001->[0, 0, 1]되네 단지 char형일뿐.
    //val list2 = readLine()!!.split("").drop(1).dropLast(1).map { it.toInt() }
    //val list2 = readLine()!!.toList().map{it.toInt()-48}
    //val list2 = readLine()!!.toCharArray()!!.toList()
 
 
    //val afterTime = System.currentTimeMillis()
    //val secDiffTime = (afterTime - beforeTime) / 1000
    // println("시간차이(m) : $secDiffTime")
    val(n,m)= readLine()!!.split(" ").map{it.toInt()}
 
    val graph = mutableListOf<MutableList<Int>>()
    for(i in 0 until n){
        graph.add(readLine()!!.map{it.toInt()-48}.toMutableList())
    }
    println(graph)
 
    var result = 0
    for(i in 0 until n){
        for(j in 0 until m){
            if(dfs(graph,i,j,n,m)){
                result += 1
            }
        }
    }
    print(result)
 
}
cs