dev/algorithm

BOJ / 1485번 / 정사각형 [Go][Python3]

crscnt 2021. 2. 10. 21:00

👩🏻‍💻 문제

 

1485번: 정사각형

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 네 줄로 이루어져 있으며, 점의 좌표가 한 줄에 하나씩 주어진다. 점의 좌표는 -100,000보다 크거나 같고, 100,000보다 작거나 같

www.acmicpc.net


✍🏻 풀이

🎨 Go

// https://www.acmicpc.net/problem/1485
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
)

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

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

	for i := 0; i < t; i++ {
		var coordinates []coordinateFormat
		for j := 0; j < 4; j++ {
			var coordinate = coordinateFormat{}
			fmt.Fscanln(reader, &coordinate.x, &coordinate.y)
			coordinates = append(coordinates, coordinate)
		}
		sort.Slice(coordinates, func(i, j int) bool {
			if coordinates[i].x < coordinates[j].x {
				return true
			} else if coordinates[i].x == coordinates[j].x {
				return coordinates[i].y < coordinates[j].y
			}
			return false
		})
		fmt.Fprintln(writer, checkSquare(coordinates))
	}
}

type coordinateFormat struct {
	x float64
	y float64
}

// if square return 1 else return 0
func checkSquare(c []coordinateFormat) int {
	sideOne := math.Pow(c[0].x-c[1].x, 2.0) + math.Pow(c[0].y-c[1].y, 2.0)
	sideTwo := math.Pow(c[1].x-c[3].x, 2.0) + math.Pow(c[1].y-c[3].y, 2.0)
	if sideOne != sideTwo {
		return 0
	}
	sideThree := math.Pow(c[3].x-c[2].x, 2.0) + math.Pow(c[3].y-c[2].y, 2.0)
	if sideTwo != sideThree {
		return 0
	}
	sideFour := math.Pow(c[2].x-c[0].x, 2.0) + math.Pow(c[2].y-c[0].y, 2.0)
	if sideThree != sideFour {
		return 0
	}
	diagonalOne := math.Pow(c[0].x-c[3].x, 2.0) + math.Pow(c[0].y-c[3].y, 2.0)
	diagonalTwo := math.Pow(c[2].x-c[1].x, 2.0) + math.Pow(c[2].y-c[1].y, 2.0)
	if diagonalOne != diagonalTwo || sideOne+sideTwo != diagonalOne {
		return 0
	}
	return 1
}

🎨 Python3

# https://www.acmicpc.net/problem/1485
import sys

def check_square(c):
    side_one = (c[0][0] - c[1][0])**2 + (c[0][1] - c[1][1])**2
    side_two = (c[1][0] - c[3][0])**2 + (c[1][1] - c[3][1])**2
    if side_one != side_two:
        return 0
    side_three = (c[3][0] - c[2][0])**2 + (c[3][1] - c[2][1])**2
    if side_two != side_three:
        return 0
    side_four = (c[2][0] - c[0][0])**2 + (c[2][1] - c[0][1])**2
    if side_three != side_four:
        return 0
    diagonal_one = (c[0][0] - c[3][0])**2 + (c[0][1] - c[3][1])**2
    diagonal_two = (c[2][0] - c[1][0])**2 + (c[2][1] - c[1][1])**2
    if diagonal_one != diagonal_two or side_one + side_two != diagonal_one:
        return 0
    return 1

if __name__ == "__main__":
    t = int(sys.stdin.readline())
    for i in range(t):
        coordinates = []
        for j in range(4):
            x, y = list(map(int,sys.stdin.readline().split()))
            coordinates.append((x, y))
        coordinates.sort(key=lambda a: (a[0], a[1]))
        print(check_square(coordinates))
728x90