Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 3184๋ฒˆ - ์–‘ (์‹ค๋ฒ„1) (DFS)

๊ฐ์ž ๐Ÿฅ” 2023. 2. 28. 14:26
๋ฐ˜์‘ํ˜•

์นœ๊ตฌ์™€ DFS / BFS์— ๋Œ€ํ•œ ๊ณ ์ฐฐ์„ ํ•œ ํšจ๊ณผ๋ฅผ ํ†กํ†กํžˆ ๋ณด๋Š”๊ฑธ๊นŒ? ์ด์ œ DFS์™€ BFS๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ๊ตฌ๋ณ„ํ•  ์ค„ ์•Œ๊ณ  ๋ฌธ์ œ๊ฐ€ ์‰ฝ๊ณ  ๋น ๋ฅด๊ฒŒ ํ’€๋ฆฐ๋‹ค..!

 

โšซ๏ธ ๋ฌธ์ œ

https://www.acmicpc.net/problem/3184

 

3184๋ฒˆ: ์–‘

์ฒซ ์ค„์—๋Š” ๋‘ ์ •์ˆ˜ R๊ณผ C๊ฐ€ ์ฃผ์–ด์ง€๋ฉฐ(3 ≤ R, C ≤ 250), ๊ฐ ์ˆ˜๋Š” ๋งˆ๋‹น์˜ ํ–‰๊ณผ ์—ด์˜ ์ˆ˜๋ฅผ ์˜๋ฏธํ•œ๋‹ค. ๋‹ค์Œ R๊ฐœ์˜ ์ค„์€ C๊ฐœ์˜ ๊ธ€์ž๋ฅผ ๊ฐ€์ง„๋‹ค. ์ด๋“ค์€ ๋งˆ๋‹น์˜ ๊ตฌ์กฐ(์šธํƒ€๋ฆฌ, ์–‘, ๋Š‘๋Œ€์˜ ์œ„์น˜)๋ฅผ ์˜๋ฏธํ•œ๋‹ค.

www.acmicpc.net

 

โšซ๏ธ ๋‚˜์˜ ํ’€์ด

์•ž์„œ ํ’€์—ˆ๋˜ DFS ๋ฌธ์ œ ์œ ํ˜•๊ณผ ๊ณ„์† ๋น„์Šทํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ˆ˜์›”ํ•˜๊ฒŒ ํ’€์ด๋ฅผ ์ƒ๊ฐํ•ด๋ƒˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์นœ๊ตฌ์™€ ์ด์•ผ๊ธฐ ๋‚˜๋ˆด๋˜ ๋ถ€๋ถ„์„ ์ž˜ ์ƒ๊ฐํ•˜๋ฉด์„œ ํ‘ธ๋‹ˆ๊นŒ ๊ธˆ๋ฐฉ ํ’€๋ฆฐ๋‹ค.. ์˜ฌ๋ ˆ ์˜ฌ๋ ˆ

์˜์—ญ๋งˆ๋‹ค ์–‘๊ณผ ๋Š‘๋Œ€์˜ ์ˆ˜๋ฅผ ๋”ฐ๋กœ ์„ธ์–ด์ค˜์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์—, for ๋ฌธ์„ ๋Œ๋ ค์„œ ์˜์—ญ๋ณ„๋กœ ํƒ์ƒ‰ํ•ด์ฃผ์–ด์•ผํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค. ์˜์—ญ๋งˆ๋‹ค ํƒ์ƒ‰์„ ๋งˆ์น˜๋ฉด ์ „๋ถ€ # (์šธํƒ€๋ฆฌ)๋กœ ๊ฐ’์„ ๋ฐ”๊ฟ”์ฃผ๋ฉด์„œ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ฃผ์—ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ฐ ์˜์—ญ๋งˆ๋‹ค ์–‘๊ณผ ๋Š‘๋Œ€์˜ ์ˆ˜๋ฅผ ๋น„๊ตํ•ด์„œ ์ด answer์„ ๊ตฌํ•ด์ฃผ์—ˆ๋‹ค.!

๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์ „ ์•„๋ž˜์ฒ˜๋Ÿผ ๊ทธ๋ฆผ์„ ๊ทธ๋ ธ๋‹ค.

์ด๊ฒƒ์„ ๊ทธ๋Œ€๋กœ ์ฝ”๋“œ๋กœ ์˜ฎ๊ธฐ๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ์ •๋‹ต์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค!

 

โšซ๏ธ ์ •๋‹ต์ฝ”๋“œ 

import Foundation

let rc = readLine()!.split(separator: " ").map{ Int($0)! }
var field = [[String]]()
for _ in 0..<rc[0] {
    field.append(readLine()!.map{ String($0) })
}

let dx = [-1, 1, 0, 0]
let dy = [0, 0, -1, 1]

var oCnt = 0
var vCnt = 0
var answer = [0, 0]

private func dfs(x: Int, y: Int) {
    switch field[x][y] {
    case "o":
        oCnt += 1
    case "v":
        vCnt += 1
    default:
        break
    }

    field[x][y] = "#"

    for i in 0..<4 {
        let nx = x + dx[i]
        let ny = y + dy[i]

        if nx < 0 || ny < 0 || nx >= rc[0] || ny >= rc[1] {
            continue
        }

        if field[nx][ny] != "#" {
            dfs(x: nx, y: ny)
        }
    }
}

for i in 0..<rc[0] {
    for j in 0..<rc[1] {
        if field[i][j] != "#" {
            oCnt = 0
            vCnt = 0
            dfs(x: i, y: j)

            if vCnt >= oCnt {
                answer[1] += vCnt
            } else {
                answer[0] += oCnt
            }
        }
    }
}

print("\(answer[0]) \(answer[1])")
๋ฐ˜์‘ํ˜•