๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Swift ์ž๋ฌผ์‡ ์™€ ์—ด์‡  2020 kakao

by Jouureee 2022. 5. 13.

๋ฌธ์ œ : 

https://programmers.co.kr/learn/courses/30/lessons/60059

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ž๋ฌผ์‡ ์™€ ์—ด์‡ 

[[0, 0, 0], [1, 0, 0], [0, 1, 1]] [[1, 1, 1], [1, 1, 0], [1, 0, 1]] true

programmers.co.kr

 

swift ์ฝ”๋“œ :

//
//  main.swift
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2022/05/12.
//

import Foundation

func rotation(_ arr: [[Int]]) -> [[Int]] { // ์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ 90๋„ ํšŒ์ „
    var resultArr = Array(repeating: Array(repeating: 0, count: arr[0].count), count: arr.count)
    for row in 0..<arr.count {
        for column in 0..<arr[row].count {
            resultArr[column][arr.count - row - 1] = arr[row][column]
        }
    }
    return resultArr
}

func attach(_ x: Int, _ y: Int, _ M: Int, _ key: [[Int]], _ map: [[Int]]) -> [[Int]] {
    var map = map
    for i in 0..<M {
        for j in 0..<M {
            map[x+i][y+j] += key[i][j]
        }
    }
    return map
}

func check(_ map: [[Int]], _ M: Int, _ N: Int) -> Bool {
    for i in 0..<N {
        for j in 0..<N {
            if map[M+i][M+j] != 1 { return false }
        }
    }
    return true
}

func detach(_ x: Int, _ y: Int, _ M: Int, _ key: [[Int]], _ map: [[Int]]) -> [[Int]] {
    var map = map
    for i in 0..<M {
        for j in 0..<M {
            map[x+i][y+j] -= key[i][j]
        }
    }
    return map
}

func solution(_ key:[[Int]], _ lock:[[Int]]) -> Bool {
    var rotateArr = key
    let M = key.count
    let N = lock.count
    
    var map = Array(repeating: Array(repeating: 0, count: M * 2 + N), count: M * 2 + N)
    for i in 0..<N {
        for j in 0..<N {
           map[M+i][M+j] = lock[i][j]
        }
    }
    for _ in 0..<4 {
        rotateArr = rotation(rotateArr)
        //atach
        for i in 1..<M+N {
            for j in 1..<M+N {
                map = attach(i, j, M, rotateArr, map)
                if (check(map, M, N)) { return true }
                map = detach(i, j, M, rotateArr, map)
            }
        }
    }
    return false
}

//print(solution([[0, 0, 0], [1, 0, 0], [0, 1, 1]], [[1, 1, 1], [1, 1, 0], [1, 0, 1]]))

 

๊ฒฐ๊ณผ :

๋Œ“๊ธ€