๋ฐฑ์ค€ - ํ–‰๋ ฌ(Swift)

2022. 10. 27. 10:11ใ†Algorithm

๋ฐฑ์ค€ - ํ–‰๋ ฌ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://www.acmicpc.net/problem/1080

 

1080๋ฒˆ: ํ–‰๋ ฌ

์ฒซ์งธ ์ค„์— ํ–‰๋ ฌ์˜ ํฌ๊ธฐ N M์ด ์ฃผ์–ด์ง„๋‹ค. N๊ณผ M์€ 50๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ํ–‰๋ ฌ A๊ฐ€ ์ฃผ์–ด์ง€๊ณ , ๊ทธ ๋‹ค์Œ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ํ–‰๋ ฌ B๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

 

 ๋‚˜์˜ ํ’€์ด

 

๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š”๋ฐ ๋ฐฉ๋ฒ•์ด ๋– ์˜ค๋ฅด์ง€์•Š์•„์„œ ๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ์ฐธ๊ณ ํ–ˆ๋‹ค.

 

์ด ๋ฌธ์ œ๋Š” 0,0๋ถ€ํ„ฐ ๋๊นŒ์ง€ ํƒ์ƒ‰ํ•˜๋ฉด์„œ targetํ–‰๋ ฌ๊ณผ ์›์†Œ๊ฐ’์ด ๋‹ค๋ฅด๋‹ค๋ฉด 3x3๋งŒํผ์„ ๋’ค์ง‘์–ด์ฃผ๋Š” ๊ฒƒ์„ ๋ฐ˜๋ณตํ•˜๋ฉด ๋œ๋‹ค.

๊ทธ๋ฆฌ๊ณ  (x, y)ํ–‰๋ ฌ์ด ์žˆ์„๋•Œ y-3์—์„œ y-1๊นŒ์ง€ ํ•œ๋ฒˆ์— ํƒ์ƒ‰ํ•˜๊ณ  y-2์—์„œ๋Š” ์ธ๋ฑ์Šค๊ฐ€ ์ดˆ๊ณผ๋˜๊ธฐ ๋•Œ๋ฌธ์— ํ™•์ธํ•˜์ง€ ์•Š์•„์„œ y-3์ผ๋•Œ y-2์™€ y-1์˜ ๊ฐ’์„ ํ™•์ธํ•ด์•ผ ํ•œ๋‹ค. ์ด๋•Œ targetํ–‰๋ ฌ์˜ ์›์†Œ๊ฐ’๊ณผ ๋‹ค๋ฅด๋‹ค๋ฉด returnํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

import Foundation

let input = readLine()!.components(separatedBy: " ").map{Int($0)!}
let row = input[0], col = input[1]
var originBoard = [[Int]](repeating: [], count: row)
var targetBoard = [[Int]](repeating: [], count: row)
var count = 0

for i in 0..<input[0] * 2 {
    let row = readLine()!
    if i < input[0] {
        for c in row {
            originBoard[i].append(Int(String(c))!)
        }
    } else {
        for c in row {
            targetBoard[i-input[0]].append(Int(String(c))!)
        }
    }
}


func reverseBoard(_ board: inout [[Int]], _ row: Int, _ col: Int) {
    for r in row..<row+3 {
        for c in col..<col+3 {
            board[r][c] = board[r][c] == 0 ? 1 : 0
        }
    }
}

func changeBoard() {
	// ํ–‰, ์—ด์˜ ๊ฐ’์ด 3๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ๋ฆฌํ„ด
    if input[0] < 3 || input[1] < 3 { return }
    
    for r in 0..<input[0]-2 {
        for c in 0..<input[1]-2 {
            if originBoard[r][c] != targetBoard[r][c] {
                reverseBoard(&originBoard, r, c)
                count += 1
            }
            
            if c == input[1]-3 {
                for i in input[1]-3..<input[1] {
                    if originBoard[r][i] != targetBoard[r][i] { return }
                }
            }
        }
    }
    
}

func main() {
    changeBoard()
    if originBoard == targetBoard {
        print(count)
    } else {
        print(-1)
    }
}

main()

 

 

 

 ํ”ผ๋“œ๋ฐฑ

 

2์ฐจ์›๋ฐฐ์—ด์„ ๋ฐ›์„๋•Œ ๋นˆ ๊ฐ’์„ ์ƒ์„ฑํ•˜๊ณ  appendํ•ด์„œ ๋ฐ›์•˜๋Š”๋ฐ ๊ณ„์† ๋Ÿฐํƒ€์ž„์—๋Ÿฌ๊ฐ€ ๋‚˜์™”๋‹ค.. ์ผ๋‹จ์€ ์œ„ ํ’€์ด์ฒ˜๋Ÿผ ๋ฐ›์€ ReadLine์— ๋Œ€ํ•ด์„œ for๋ฌธ์„ ๋Œ๋ฉด์„œ i์ธ๋ฑ์Šค๋กœ ์‚ฝ์ž…์„ ํ•ด์•ผ๊ฒ ๋‹ค.