💬 문제
https://www.acmicpc.net/problem/21608
💬 풀이
import Foundation
func solution21608(){letn=Int(readLine()!)!
varboard=Array(repeating:Array(repeating:0, count: n), count: n)varsloDict:[Int:[Int]]=[:]varnearDict:[[Int]:Int]=[:]varsLikeDict:[Int:[Int]]=[:]foriin0..<n {forjin0..<n {if(i >0 && i < n -1) && (j >0 && j < n -1){nearDict[[i, j]]=4}elseif(i ==0 && j ==0) || (i ==0 && j == n -1) || (i == n -1 && j == n -1) || (i == n -1 && j ==0){nearDict[[i, j]]=2}else{nearDict[[i, j]]=3}}}for_in0..<Int(pow(Double(n),2)){letsArr=readLine()!.components(separatedBy:.whitespaces)lets=Int(sArr[0])!
letlikes=sArr[1...4].map({Int(String($0))! })varlikeDict:[[Int]:Int]=[:]sLikeDict[s]= likes
forlin likes {
// 인접 좌표 구하기
ifsloDict[l]!=nil{letlo=sloDict[l]!
letu=[lo[0]-1,lo[1]]letd=[lo[0]+1,lo[1]]letl=[lo[0],lo[1]-1]letr=[lo[0],lo[1]+1]foriin[u, d, l, r]{ifi[0]<0 || i[0]> n -1 || i[1]<0 || i[1]> n -1{continue}
// 비어있는 칸일 경우에만 검사하기
ifboard[i[0]][i[1]]==0{iflikeDict[i]==nil{likeDict[i]=1}else{likeDict[i]! +=1}}}}}if likeDict.keys.isEmpty {
// 가장 빈 칸이 많으면서 행이 작은 칸으로 배치
letnear= nearDict.sorted(by:{if $0.value == $1.value {if $0.key[0]== $1.key[0]{return $0.key[1]< $1.key[1]}else{return $0.key[0]< $1.key[0]}}else{return $0.value > $1.value
}}).first!.key
board[near[0]][near[1]]= s
sloDict[s]=[near[0],near[1]]
nearDict.removeValue(forKey:[near[0],near[1]])ifnearDict[[near[0]+1,near[1]]]!=nil{nearDict[[near[0]+1,near[1]]]! -=1}ifnearDict[[near[0]-1,near[1]]]!=nil{nearDict[[near[0]-1,near[1]]]! -=1}ifnearDict[[near[0],near[1]+1]]!=nil{nearDict[[near[0],near[1]+1]]! -=1}ifnearDict[[near[0],near[1]-1]]!=nil{nearDict[[near[0],near[1]-1]]! -=1}}else{letlo= likeDict.sorted(by:{
// 좋아하는 학생이 인접한 칸에 가장 많은 칸
if $0.value == $1.value {
// 1을 만족하는 칸이 여러 개이면, 인접한 칸 중에서 비어있는 칸이 가장 많은 칸
ifnearDict[$0.key]! ==nearDict[$1.key]! {
// 2를 만족하는 칸도 여러 개인 경우에는 행의 번호가 가장 작은 칸
if $0.key[0]== $1.key[0]{
// 그러한 칸도 여러 개이면 열의 번호가 가장 작은 칸
return $0.key[1]< $1.key[1]}else{return $0.key[0]< $1.key[0]}}else{returnnearDict[$0.key]! >nearDict[$1.key]!
}}else{return $0.value > $1.value
}}).first!.key
board[lo[0]][lo[1]]= s
sloDict[s]=[lo[0],lo[1]]
nearDict.removeValue(forKey:[lo[0],lo[1]])ifnearDict[[lo[0]+1,lo[1]]]!=nil{nearDict[[lo[0]+1,lo[1]]]! -=1}ifnearDict[[lo[0]-1,lo[1]]]!=nil{nearDict[[lo[0]-1,lo[1]]]! -=1}ifnearDict[[lo[0],lo[1]+1]]!=nil{nearDict[[lo[0],lo[1]+1]]! -=1}ifnearDict[[lo[0],lo[1]-1]]!=nil{nearDict[[lo[0],lo[1]-1]]! -=1}}}varsum=0forsin sLikeDict {letlo=sloDict[s.key]!
varcnt=0forsnin s.value {letu=[lo[0]-1,lo[1]]letd=[lo[0]+1,lo[1]]letl=[lo[0],lo[1]-1]letr=[lo[0],lo[1]+1]foriin[u, d, l, r]{ifi[0]<0 || i[0]> n -1 || i[1]<0 || i[1]> n -1{continue}ifboard[i[0]][i[1]]== sn {
cnt +=1}}}if cnt >0{
sum +=Int(pow(10,Double(cnt -1)))}}print(sum)}
💬 문제https://www.acmicpc.net/problem/21608
💬 풀이