ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

1992๋ฒˆ: ์ฟผ๋“œํŠธ๋ฆฌ

์ฒซ์งธ ์ค„์—๋Š” ์˜์ƒ์˜ ํฌ๊ธฐ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆซ์ž N ์ด ์ฃผ์–ด์ง„๋‹ค. N ์€ ์–ธ์ œ๋‚˜ 2์˜ ์ œ๊ณฑ์ˆ˜๋กœ ์ฃผ์–ด์ง€๋ฉฐ, 1≤N ≤64์˜ ๋ฒ”์œ„๋ฅผ ๊ฐ€์ง„๋‹ค. ๋‘ ๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ๋Š” ๊ธธ์ด N ์˜ ๋ฌธ์ž์—ด์ด N ๊ฐœ ๋“ค์–ด์˜จ๋‹ค. ๊ฐ ๋ฌธ์ž์—ด์€ 0 ๋˜๋Š”

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

// https://www.acmicpc.net/problem/1992
// ์ฟผ๋“œํŠธ๋ฆฌ๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พธ๋Š” ๋ฌธ์ œ
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

var (
	image  [][]string
	writer *bufio.Writer
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n int
	fmt.Fscanln(reader, &n)

	for i := 0; i < n; i++ {
		input, _ := reader.ReadString('\n') // ๊ณต๋ฐฑ ํฌํ•จํ•˜์—ฌ ์ž…๋ ฅ ๋ฐ›๊ธฐ ์œ„ํ•ด ReadString() ์‚ฌ์šฉ
		inputs := strings.Split(input, "")
		image = append(image, inputs)
	}

	quadTree(0, 0, n)
	fmt.Fprintln(writer, "")
}

func quadTree(row, col, n int) {
	first := image[row][col]
	var isComplete bool = true

	for i := row; i < row+n; i++ {
		for j := col; j < col+n; j++ {
			if i == row && j == col {
				continue
			}
			if image[i][j] != first {
				isComplete = false
				break
			}
		}
		if !isComplete {
			break
		}
	}
	if isComplete {
		fmt.Fprint(writer, first)
	} else {
		fmt.Fprint(writer, "(")
		interval := n / 2
		quadTree(row, col, interval)
		quadTree(row, col+interval, interval)
		quadTree(row+interval, col, interval)
		quadTree(row+interval, col+interval, interval)
		fmt.Fprint(writer, ")")
	}
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/1992
# ์ฟผ๋“œํŠธ๋ฆฌ๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พธ๋Š” ๋ฌธ์ œ
import sys

image = []

def quad_tree(row, col, n):
    global image
    first = image[row][col]
    is_complete = True

    for i in range(row, row+n):
        for j in range(col, col+n):
            if i == row and j == col:
                continue
            if image[i][j] != first:
                is_complete = False
                break
        if not is_complete:
            break

    if is_complete:
        print(first, end='')
    else:
        print("(", end='')
        interval = n//2
        quad_tree(row, col, interval)
        quad_tree(row, col+interval, interval)
        quad_tree(row+interval, col, interval)
        quad_tree(row+interval, col+interval, interval)
        print(")", end='')

if __name__ == "__main__":
    n = int(sys.stdin.readline())

    for i in range(n):
        image.append(list(map(int, list(sys.stdin.readline().rstrip()))))
    
    quad_tree(0, 0, n)
    print()
728x90
๋Œ“๊ธ€