๋ฌธ์ :
https://www.acmicpc.net/problem/14503
ํ์ด :
์ฒ์์ ํ์ฌ ์์น ํ์ํ๋๋ฐ arr์ 1๊ฐ์ ๋ฃ์ด์ ๊ณ์ ์ค๋ฅ๊ฐ ๋์ 1์๊ฐ๋์ ํค๋งธ๋ค .. ๊ทธ๋ฆฌ๊ณ ๋, ์ ๊ตฌ๋ถ์ ๋ฐ๋๋ก ํด์ ๋ ํค๋งธ๋ค ..
๋ฐฉํฅ ๊ฐ๋ง ์ ๋ฃ์ด์ค๋ค๋ฉด DFS ํธ๋ ๋ฐฉ์๋๋ก ํ๋ฉด ๋ ๊ฑฐ ๊ฐ๋ค !
์ผ์ชฝ ๋ฐฉํฅ์ผ๋ก ํ์ ํ๋ ค๋ฉด ๋ถ -> ์ // ์ -> ๋จ // ๋จ -> ๋ // ๋ -> ๋ถ์ผ๋ก ์ด๋ํ๋ฉด ๋๋ค.
๋ฐ๋ผ์ 0 -> 3, 3 -> 2, 2-> 1, 1 -> 0์ผ๋ก ์ด๋ํด์ผ ํ๋ค. ์ด๋ฅผ ๊ตฌํํ๋ฉด ์๋์ ๊ฐ๋ค.
func leftTurn(_ now: Int, _ i: Int) -> Int {
return (now + 3 - i) % 4 // ๋ถ - 0, ๋ - 1, ๋จ - 2, ์ - 3
}
๊ทธ๋ฆฌ๊ณ ๋ ํ์งํ ๋ ๋ท์ชฝ์ด ์ด๋์ธ์ง๋ ๊ณ์ฐํด์ค์ผ ํ๋๋ฐ ํ์ฌ ๋ฐ๋ผ๋ณด๊ณ ์๋ ๋ฐฉํฅ์์ ํ์งํ๊ฒ ๋๋ฉด
ํ์ฌ : ํ์ง
๋จ์ชฝ -> ๋ถ์ชฝ
์์ชฝ -> ๋์ชฝ
๋ถ์ชฝ -> ๋จ์ชฝ
๋์ชฝ -> ์์ชฝ
์ผ๋ก ์ด๋ํด์ผ ํ๋ค. ์ด๋ฅผ ๊ตฌํํ๋ฉด ์๋์ ๊ฐ๋ค.
let backIdx = now > 1 ? now - 2: now + 2
Swift ์ฝ๋ :
//
// main.swift
// SOMA๐ฉ๐ป๐ป
//
// Created by JoSoJeong on 2022/04/18.
//
import Foundation
var dx = [-1, 0, 1, 0]
var dy = [0, 1, 0, -1]
var line = readLine()!.split(separator: " ").map { Int(String($0))! }
var n = line[0]
var m = line[1]
var line2 = readLine()!.split(separator: " ").map { Int(String($0))! }
var r = line2[0]
var c = line2[1]
var dir = line2[2]
var cnt = 1 // ํ์ฌ๊น์ง cnt
var arr: [[Int]] = Array(repeating: [], count: n)
var visit: [[Bool]] = Array(repeating: Array(repeating: false, count: m), count: n)
for i in 0..<n {
let l = readLine()!.split(separator: " ").map { Int(String($0))! }
arr[i] = l
}
//ํ์ฌ ์์น ๋ฐฉ๋ฌธ
visit[r][c] = true
func leftTurn(_ now: Int, _ i: Int) -> Int {
return (now + 3 - i) % 4 // ๋ถ - 0, ๋ - 1, ๋จ - 2, ์ - 3
}
func dfs_clean(_ cnt: Int, _ now: Int, _ x: Int, _ y: Int) {
for i in 0..<4{
let nextD = leftTurn(now, i)
let nextX = dx[nextD] + x
let nextY = dy[nextD] + y
if (nextX >= n || nextX < 0 || nextY >= m || nextY < 0) { continue }
if (visit[nextX][nextY] == true || arr[nextX][nextY] == 1) { continue }
visit[nextX][nextY] = true
dfs_clean(cnt + 1, nextD, nextX, nextY)
}
//4๋ฒ ์ฐ์ ์คํ์ ๋๋ด๊ณ
//๋ฐ๋ก ๋ค๊ฐ ๋ฒฝ์ด๋ฉด ๋ฉ์ถค
// ์๋๋ฉด ํ์ง
let backIdx = now > 1 ? now - 2: now + 2
let backX = dx[backIdx] + x
let backY = dy[backIdx] + y
if backX < n || backX > 0 || backY < m || backY > 0 {
if arr[backX][backY] == 1 {
print(cnt)
exit(0)
}else {
dfs_clean(cnt, now, backX, backY) //ํ์ง ์ ๋ฐฉํฅ์ ๋ฐ๋์ง x
}
}
}
dfs_clean(cnt, dir, r, c)
'Algorithm๐ฐ > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] Swift 11052 ์นด๋ ๊ตฌ๋งคํ๊ธฐ DP (0) | 2022.04.19 |
---|---|
[๋ฐฑ์ค] Swift 1504 ํน์ ํ ์ต๋จ ๊ฒฝ๋ก dijkstra (0) | 2022.04.18 |
[๋ฐฑ์ค] Swift ์ผ๋น ๋ฒ ์ด์ปจ์ 6๋จ๊ณ ๋ฒ์น BFS (0) | 2022.04.17 |
[๋ฐฑ์ค] Swift 2302 ๊ทน์ฅ ์ข์ DP (0) | 2022.04.17 |
[๋ฐฑ์ค] Swift 1309 ๋๋ฌผ์ DP (0) | 2022.04.16 |
๋๊ธ