728x90
๋ฐ์ํ
Problem
Solution
ํด๋น ๋ฌธ์ ๋ ์์ ํ์์ผ๋ก ํ ์ ์๋ ๋ฌธ์ ์ ๋๋ค.
1. ํ๋ ์ด์ด์ ์์น์ ๊ฒ์ ๋๋ฌ์ ๋ ์์ง์ธ ํ์์ ์น์๋ฅผ ์๋ ค์ค ๊ตฌ์กฐ์ฒด๋ฅผ ๋ง๋ ๋ค.
struct Location {
var x:Int,y:Int
}
struct GameResult {
var count:Int,isWinnerA:Bool
}
2. board์ ๊ฐ์ฅ ์๋ฆฌ๋ฅผ 0์ผ๋ก ๊ฐ์ธ์ค๋ค.
Index out of range ์ค๋ฅ๋ฅผ ์ฝ๊ฒ ํผํ๊ธฐ ์ํด์ ์ ๋๋ค.
func wrapBoardEdges(_ board:[[Int]]) -> [[Int]] {
var wrapBoard = board
for i in 0..<board.count {
wrapBoard[i].insert(0, at: 0)
wrapBoard[i].append(0)
}
wrapBoard.insert(Array(repeating: 0, count: board[0].count+2), at: 0)
wrapBoard.append(Array(repeating: 0, count: board[0].count+2))
return wrapBoard
}
3. ์ผ์ชฝ,์ค๋ฅธ์ชฝ,์์ชฝ,์๋์ชฝ ๋ค ๋ฐฉํฅ์ผ๋ก ์์ง์ผ ๋์ ์์น๋ฅผ ๋ฏธ๋ฆฌ ๋ง๋ค์ด์ค ํจ์๋ฅผ ๊ตฌํํ๋ค.
func makeLRUD(_ loc:Location) -> [Location] {
return [Location(x: loc.x-1, y: loc.y),Location(x: loc.x+1, y: loc.y),Location(x: loc.x, y: loc.y-1),Location(x: loc.x, y: loc.y+1)]
}
4. ํ๋ ์ด์ด๊ฐ ๋ฒ๊ฐ์๊ฐ๋ฉด์ ์์ง์ผ move ํจ์๋ฅผ ๋ง๋ค์ด ์ค๋ค.
๋ฌด์กฐ๊ฑด ์ด๊ธฐ๋ ํ๋ ์ด์ด์ ์ง๋ ํ๋ ์ด์ด๊ฐ ์กด์ฌํ๋ฏ๋ก ์ด๊ธฐ๋ ๊ฒฝ์ฐ์ ์ง๋ ๊ฒฝ์ฐ์ ์ต๋๊ฐ๊ณผ ์ต์๊ฐ์ ๋ฌ๋ฆฌํด์ฃผ์ด์ผ ํ๋๋ฐ์.
๋ง์ฝ ๋ฌด์กฐ๊ฑด ์ง๋ ํ๋ ์ด์ด๋ผ๋ฉด ์ต๋ํ์ผ๋ก ๋ง์ด ์์ง์ฌ์ผ ํ๋ฏ๋ก maxCount๋ฅผ ์ต๋๊ฐ์ ์ ๋ฐ์ดํธ ํด์ฃผ๊ณ ์ด๊ธฐ๋ ํ๋ ์ด์ด๋ผ๋ฉด
์ต์ํ์ผ๋ก ์์ง์ฌ์ผ ํ๋ฏ๋ก minCount๋ฅผ ์ต์๊ฐ์ผ๋ก ์ ๋ฐ์ดํธ ํด์ค๋๋ค.
func move(_ board:[[Int]], _ count:Int,_ aLoc:Location,_ bLoc:Location) -> GameResult {
let isTurnA = count%2 == 0 ? true : false
let loc = isTurnA ? aLoc : bLoc
var minCount = Int.max
var maxCount = 0
if board[loc.x][loc.y] == 0 {
return GameResult(count: count, isWinnerA: isTurnA)
}
for l in makeLRUD(loc).filter({board[$0.x][$0.y] != 0}) {
var newBoard = board
newBoard[loc.x][loc.y] = 0
let moved = isTurnA ? move(newBoard,count+1,l,bLoc) : move(newBoard,count+1,aLoc,l)
let result = isTurnA ? moved.isWinnerA :!moved.isWinnerA
if result {
maxCount = max(maxCount,moved.count)
}else {
minCount = min(minCount,moved.count)
}
}
if minCount == Int.max && maxCount == 0 {
return GameResult(count: count, isWinnerA: isTurnA)
}
if minCount != Int.max {
return GameResult(count: minCount, isWinnerA: !isTurnA)
}
return GameResult(count: maxCount, isWinnerA: isTurnA)
}
5. ์ต์ ์ ํ๋ ์ด ๊ฐ์ ๋ฐํํ๋ค.
func solution(_ board:[[Int]], _ aloc:[Int], _ bloc:[Int]) -> Int {
let wrapBoard = wrapBoardEdges(board)
let aLoc = Location(x: aloc[0]+1, y: aloc[1]+1)
let bLoc = Location(x: bloc[0]+1, y: bloc[1]+1)
let result = move(wrapBoard, 0, aLoc, bLoc)
return result.count
}
Source Code
728x90
๋ฐ์ํ
'๐ Problem Solution > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS] ํ๋ก๊ทธ๋๋จธ์ค 124 ๋๋ผ์ ์ซ์ (0) | 2022.02.14 |
---|---|
[JS] ํ๋ก๊ทธ๋๋จธ์ค ํฐ์ผ๋ชฌ (0) | 2022.02.06 |
[Swift] 2022 KAKAO BLIND RECRUITMENT ํ๊ดด๋์ง ์์ ๊ฑด๋ฌผ (0) | 2022.01.20 |
[Swift] 2022 KAKAO BLIND RECRUITMENT ์๊ณผ ๋๋ (0) | 2022.01.19 |
[Swift] 2022 KAKAO BLIND RECRUITMENT ์๊ถ๋ํ (1) | 2022.01.19 |
๋๊ธ