Skip to content

Commit

Permalink
solve(programmers): LV3_퍼즐조각 채우기_kt
Browse files Browse the repository at this point in the history
# id: 문제 id를 숫자로 작성
# categories : 해당 문제의 유형을 ,로 구분하여 작성
# tags : 해당 문제의 태그를 ,로 구분하여 작성
# time : 해당 문제 풀이에 걸린 시간을 분단위 숫자로 작성
# try : 해당 문제에 몇번의 시도를 했는지 숫자로 작성
# help: 해당 문제에 외부의 도움을 받았는지 true/false로 작성
# url : 해당 문제의 url을 작성
id: 84021
categories: [DFS]
tags: []
time: 70
try: 1
help: false
url: https://school.programmers.co.kr/learn/courses/30/lessons/84021#
  • Loading branch information
gogumaC committed Aug 21, 2024
1 parent 29634be commit 067b546
Showing 1 changed file with 103 additions and 0 deletions.
103 changes: 103 additions & 0 deletions src/algorithmProblems/programmers/LV3_퍼즐조각_채우기_kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import kotlin.collections.ArrayDeque
class Solution {
fun solution(game_board: Array<IntArray>, table: Array<IntArray>): Int {
var answer: Int = -1

val tableP=extractPeices(table,0)
val boardP=extractPeices(game_board,1)
val filled=BooleanArray(boardP.size)
val used=BooleanArray(tableP.size)
var count=0

for(i in boardP.indices){
if(filled[i]) continue
val bp=boardP[i]
for(j in tableP.indices){
if(used[j]) continue
val tp=tableP[j]
val res=checkMatch(bp,tp)
if(res){
filled[i]=true
used[j]=true
count+=tp.size
break
}
}
}

return count
}
}

fun checkMatch(a:MutableList<Pair<Int,Int>>,b:MutableList<Pair<Int,Int>>):Boolean{

if (a.size!=b.size) return false
val c=Comparator{o1:Pair<Int,Int>,o2:Pair<Int,Int>->
if(o1.first==o2.first) o1.second-o2.second else o1.first-o2.first
}
val temp=mutableListOf<Pair<Int,Int>>()
a.sortWith(c)
b.sortWith(c)
for((x,y) in a){
temp.add(x to y)
}
loop@ for(r in 0 until 4){
val gx=temp[0].first-b[0].first
val gy=temp[0].second-b[0].second
for(i in temp.indices){
val (ax,ay)=temp[i]
val (bx,byy)=b[i]
val cgx=ax-bx
val cgy=ay-byy
if(gx!=cgx || gy!=cgy){
rotate90(temp)
temp.sortWith(c)
continue@loop
}
}
return true
}
return false
}

fun rotate90(arr:MutableList<Pair<Int,Int>>){
for(i in arr.indices){
val (x,y)=arr[i]
arr[i]=y to -x
}
}

fun extractPeices(table:Array<IntArray>,blank:Int):MutableList<MutableList<Pair<Int,Int>>>{
val pieces=mutableListOf<MutableList<Pair<Int,Int>>>()

val visited=Array(table.size){BooleanArray(table[0].size)}

val ox=listOf(1,-1,0,0)
val oy=listOf(0,0,1,-1)


//조각분리
for(i in table.indices){
for(j in table[0].indices){
if(visited[i][j] || table[i][j]==blank) continue
visited[i][j]=true
pieces.add(mutableListOf(i to j))
val s=ArrayDeque<Pair<Int,Int>>()
s.add(i to j)
while(s.isNotEmpty()){
val (cx,cy)=s.removeLast()
for(k in 0 until 4){
val nx=cx+ox[k]
val ny=cy+oy[k]
if(nx in 0 until table.size && ny in 0 until table[0].size&& !visited[nx][ny] &&table[nx][ny]==table[cx][cy]){
visited[nx][ny]=true
pieces.last().add(nx to ny)
s.add(nx to ny)
}
}
}
}
}

return pieces
}

0 comments on commit 067b546

Please sign in to comment.