From 365649ddce9df29b1471c3f08c737cde8ff2f424 Mon Sep 17 00:00:00 2001 From: SSOOYA Date: Thu, 12 Oct 2023 13:56:16 +0900 Subject: [PATCH] =?UTF-8?q?reference/#166:=20=EC=B0=B8=EA=B3=A0=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...53\241\234 \352\261\264\354\204\244.swift" | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git "a/AlgorithmReview/Programmers/Lv3/\352\262\275\354\243\274\353\241\234 \352\261\264\354\204\244.swift" "b/AlgorithmReview/Programmers/Lv3/\352\262\275\354\243\274\353\241\234 \352\261\264\354\204\244.swift" index b627e7b..835befc 100644 --- "a/AlgorithmReview/Programmers/Lv3/\352\262\275\354\243\274\353\241\234 \352\261\264\354\204\244.swift" +++ "b/AlgorithmReview/Programmers/Lv3/\352\262\275\354\243\274\353\241\234 \352\261\264\354\204\244.swift" @@ -7,36 +7,40 @@ import Foundation -func timeout(_ board:[[Int]]) -> Int { +func reference(_ board:[[Int]]) -> Int { - var visit = [[Bool]](repeating: [Bool](repeating: false, count: board.count), count: board.count) + let size = board.count + var board = board + var dp = [[Int]](repeating: [Int](repeating: size*size*500, count: board.count), count: board.count) var ans = Int.max - func valid(_ i: Int, _ j: Int) -> Bool { - i < board.count && i >= 0 && j < board.count && j >= 0 && board[i][j] == 0 && !visit[i][j] - } - - func move(_ i: Int, _ j: Int, _ d: (Int, Int), _ s: Int, _ c: Int) { + func move(_ i: Int, _ j: Int, _ d: (Int, Int), _ cost: Int) { - if i == board.count-1 && j == board.count-1 { - ans = min(ans, 100*s + 500*c); return - } else if 100*s + 500*c >= ans { + if i == size-1 && j == size-1 { + ans = min(ans, cost) + return + } else if dp[i][j] < cost { return } - for coord in [(1,0),(-1,0),(0,1),(0,-1)] { + dp[i][j] = cost + + for coord in [(0,1),(1,0),(0,-1),(-1,0)] { let row = coord.0 + i, col = coord.1 + j - if valid(row, col){ - visit[row][col] = true - let corner = d == coord ? c : c+1 - move(row,col,coord,s+1,corner) - visit[row][col] = false + if row < board.count && row >= 0 && col < board.count && col >= 0 && board[row][col] == 0 { + board[row][col] = -1 + if d == coord { + move(row,col,coord,cost+100) + } else { + move(row,col,coord,cost+600) + } + board[row][col] = 0 } } } - visit[0][0] = true - move(0,0,(0,0),0,-1) + board[0][0] = -1 + move(0,0,(0,0),0) - return ans + return ans - 500 }