๋ฐฑ์ค€ - ๋กœ๋ด‡ ์ฒญ์†Œ๊ธฐ(Swift)

2022. 11. 14. 11:19ใ†Algorithm

๋ฐฑ์ค€ - ๋กœ๋ด‡ ์ฒญ์†Œ๊ธฐ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

14503๋ฒˆ: ๋กœ๋ด‡ ์ฒญ์†Œ๊ธฐ

๋กœ๋ด‡ ์ฒญ์†Œ๊ธฐ๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ฒญ์†Œํ•˜๋Š” ์˜์—ญ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋กœ๋ด‡ ์ฒญ์†Œ๊ธฐ๊ฐ€ ์žˆ๋Š” ์žฅ์†Œ๋Š” N×M ํฌ๊ธฐ์˜ ์ง์‚ฌ๊ฐํ˜•์œผ๋กœ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์œผ๋ฉฐ, 1×1ํฌ๊ธฐ์˜ ์ •์‚ฌ๊ฐํ˜• ์นธ์œผ๋กœ ๋‚˜๋ˆ„์–ด

www.acmicpc.net

 

 

 

 ๋‚˜์˜ ํ’€์ด

 

์ฒ˜์Œ์—๋Š” ์™„์ „ํƒ์ƒ‰์œผ๋กœ DFS๋กœ ํ’€๋ ค๊ณ  ํ–ˆ์œผ๋‚˜ ์˜ˆ์ œ2๋ฅผ ๋ณด๋‹ˆ 0์˜ ์ˆ˜๊ฐ€ ๋ง‰ํ˜€์žˆ์ง€์•Š์€๋ฐ ์ „์ฒด๊ฐ€ ์•„๋‹Œ ๊ฒƒ์„ ๋ณด๊ณ  ์ •ํ™•ํ•˜๊ฒŒ ๊ตฌํ˜„์„ ํ•ด์•ผํ•˜๋Š” ๋ฌธ์ œ์ธ ๊ฒƒ์„ ์•Œ์•˜๋‹ค. ๊ฐ„๋‹จํžˆ ์ƒ๊ฐํ•ด๋ณด๋ฉด ๊ธธ์ด์—†์„๋•Œ ์ญ‰ ๊ฐ€๋‹ค๊ฐ€ ๋ง‰ํ˜”์„๋•Œ ๋’ค์ชฝ์ด 1์ด๋ผ๋ฉด ๋ฐ”๋กœ breakํ•ด์•ผํ•˜๋Š” ์ƒํ™ฉ์ด๊ธฐ ๋•Œ๋ฌธ์— ์™„์ „ํƒ์ƒ‰์ด ์•„๋‹Œ ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

 

ํ•˜์ง€๋งŒ ๋ฐฉํ–ฅ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋ฅผ ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์–ด์„œ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ์ฐธ๊ณ ํ–ˆ๋Š”๋ฐ ๋ฐฉํ–ฅ์— ๋Œ€ํ•œ ๋ณ€์ˆ˜๋ฅผ dx, dy์— ๋„ฃ์Œ์œผ๋กœ์จ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์ „์ง„ํ•  ๋•Œ์™€ ํ›„์ง„ํ•  ๋•Œ ํ˜„์žฌ ๋ฐฉํ–ฅ์„ ์ธ๋ฑ์Šค๋กœ ๋‘ ์œผ๋กœ์จ ์‰ฝ๊ฒŒ ๊ตฌํ˜„์„ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.

 

import Foundation

let input = readLine()!.components(separatedBy:" ").map{Int($0)!}
let N = input[0], M = input[1]
let input2 = readLine()!.components(separatedBy:" ").map{Int($0)!}
var curR = input2[0], curC = input2[1], curD = input2[2] // ํ˜„์žฌ x, y์ขŒํ‘œ์™€ ๋ฐฉํ–ฅ
var map = [[Int]]()
for _ in 0..<N {
    map.append(readLine()!.components(separatedBy:" ").map{Int($0)!})
}


// ๋ถ ๋™ ๋‚จ ์„œ
let dx = [-1, 0, 1, 0]
let dy = [0, 1, 0, -1]
var cnt = 0 // ์ „ํ™˜ํ•œ ํšŸ์ˆ˜
var result = 1
map[curR][curC] = 2
while true {
    // ๋ฐฉํ–ฅ ์ „ํ™˜
    curD -= 1
    if curD == -1 { curD = 3 }
    
    // ๋ฐฉํ–ฅ ์ „ํ™˜ํ•œ ๊ฐ’
    let nx = curR + dx[curD]
    let ny = curC + dy[curD]
    // ๋ฒฝ์ด๊ฑฐ๋‚˜ ๋ฐฉ๋ฌธํ•œ ๊ฐ’์ด ์•„๋‹ ๋•Œ
    if map[nx][ny] != 1 && map[nx][ny] != 2 {
        map[nx][ny] = 2
        result += 1
        curR = nx
        curC = ny
        cnt = 0
        continue
    } else {
        cnt += 1 // ๋ฒฝ์ด๊ฑฐ๋‚˜ ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด cnt๋งŒ ์ฆ๊ฐ€
    }
    if cnt == 4 {
        curR -= dx[curD]
        curC -= dy[curD]
        cnt = 0
        // ๋’ค๋กœ ๊ฐ„ ๊ฐ’์ด ๋ฒฝ์ด๋ผ๋ฉด ์ข…๋ฃŒ
        if map[curR][curC] == 1 {
            break
        } 
    }
}

print(result)