Problem
Solution
1. ์ฌ์ดํด์ ๋ํ ๊ฐ๋ ์ ์ดํดํ๋ค.
์ฌ์ดํด์ ์ฒ์ ์์ํ ์นธ์์ ์ฒ์ ์์ํ ๋ฐฉํฅ์ผ๋ก ๋ค์ ๋๋์ ์ฌ ๋ ์ฌ์ดํด์ด ํ์ฑ๋ฉ๋๋ค.
์ฆ (0,0)์์ ์ค๋ฅธ์ชฝ์ผ๋ก ๋น์ ์๊ณ ๋ค์ (0,0)์์ ์ค๋ฅธ์ชฝ์ผ๋ก ๋ค์ด์ค๋ ๋น์ด ์๋ค๋ฉด ์ฌ์ดํด์ ๋๋ค.
2. ์์น์ ๋ฐฉํฅ์ ๊ธฐ์ตํ Location ๊ตฌ์กฐ์ฒด๋ฅผ ๋ง๋ค์ด์ค๋ค.
struct Location:Equatable {
var x:Int,y:Int,d:String
}
3. ์ฌ์ดํด์ ๊ตฌํ๋๋ฐ ํ์ํ ๊ฐ๋ค์ ๋ฏธ๋ฆฌ ์ ์ํด๋๋๋ค.
dValue: ๋ฐฉํฅ์ ๋ฐ๋ผ ์์น๊ฐ ๋ฐ๋์ด์ผํ ๊ฐ
next: ์งํ๋ ๋ฐฉํฅ์ด ์ฐํ์ ์ขํ์ ์ง์ง์ ๋ฐ๋ผ ๋ฐ๋ ๋ฐฉํฅ
answer: ์ฌ์ดํด์ ๊ธธ์ด๋ค
g: grid์ ์ด์ค ๋ฐฐ์ด
visited: ๊ฐ ์นธ์ ๋ฐฉํฅ๋ณ ๋ฐฉ๋ฌธ์ด๋ ฅ์ ์ ์ฅ
let dValue = ["up":(0,-1),"down":(0,1),"left":(-1,0),"right":(1,0)]
let next:[String:[String:String]] = ["L":["down":"right","right":"up","up":"left","left":"down"],"R":["down":"left","right":"down","up":"right","left":"up"],"S":["down":"down","right":"right","up":"up","left":"left"]]
var answer:[Int] = []
let g = grid.map{$0.map{String($0)}}
var visited = Array(repeating: Array(repeating:["up":false,"down":false,"right":false,"left":false], count: g[0].count), count: g.count)
4. ๋ชจ๋ ์นธ์์ ๋ชจ๋ ๋ฐฉํฅ์ ๋ฐ๋ผ ์ฌ์ดํด์ ๋ง๋๋์ง ํ์ธํ๋ค.
3์ค ํฌ๋ฌธ ๋ชจ๋ x,y์์์ ์,์๋,์ค๋ฅธ์ชฝ,์ผ์ชฝ์ผ๋ก ํ์ธํฉ๋๋ค.
๋ง์ฝ ์ด๋ฏธ ๋ฐฉ๋ฌธํ๋ค๋ฉด break๋ฅผ ํ๊ณ ๊ทธ๊ฒ ์๋๋ผ๋ฉด ๋ค์ ์์น๋ก ๋์ด๊ฐ๋๋ก ํฉ๋๋ค.
๊ทธ๋ฌ๋ค๊ฐ ๋งจ ์ฒ์ ์์๋ ์์น๊ฐ ๋๋์์๋ค๋ฉด count๋ฅผ answer์ ๋ฃ์ด์ค๋๋ค.
for y in 0..<g.count {
for x in 0..<g[0].count {
for d in dValue.keys {
let first = Location(x: x, y: y, d: d)
var location:Location = first
var count:Int = 0
while true {
if visited[location.y][location.x][location.d]! { break }
visited[location.y][location.x][location.d] = true
count += 1
let direction = g[location.y][location.x]
location.d = next[direction]![location.d]!
location.x += dValue[location.d]!.0
location.y += dValue[location.d]!.1
location.x = location.x < 0 ? g[0].count-1 : location.x%g[0].count
location.y = location.y < 0 ? g.count-1 : location.y%g.count
if location == first && count != 0{
answer.append(count)
break
}
}
}
}
}
5. answer๋ฅผ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํด ๋ฐํํ๋ค.
return answer.sorted()
Source Code
P.S
์ด๊ฑด 2๋จ๊ณ๋ผ๊ณ ๋ณด๊ธฐ์ ์ด๋ ค์ธ ๊ฒ ๊ฐ๋ค.... 3๋จ๊ณ์์๋ ์กฐ๊ธ ๋์ด๋ ์๋ ๋ฌธ์ ๊ฐ์๋ฐ...
์ฒ์์ ์ฌ์ดํด์ ๋ํ ๊ฐ๋ ์ ์ดํดํ ๋ 1 - 2 - 3 - 4 ์ 5 - 1 - 2 - 3 - 4 ๋ ๋ค๋ฅธ ์ฌ์ดํด์ด๋ผ๊ณ ์๊ฐํ๊ณ
๋ฐฉ๋ฌธ์ด๋ ฅ์ ๋น์ด ์ฒ์ ์์ํ ๋๋ง๋ค ์ด๊ธฐํํด์คฌ๋๋ฐ.. ๊ทธ๊ฒ ์๋์๋ค... ๊ทธ๊ฒ๋ง ๋ฐ๋ก ์์๋๋ผ๋ ๋นจ๋ฆฌ ํ์์ํ ๋ฐ..
Swift๋ก๋ 2๋ฒ์งธ๋ก ๋ฌธ์ ๋ฅผ ํผ ์ฌ๋์ด์ฌ์ ๋ฟ๋ฏํ๋ค...ใ ใ
๋๊ธ