Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

main

[백준-2564번/Java] 경비원 본문

Algorithm

[백준-2564번/Java] 경비원

1984 2022. 11. 13. 11:00

* 좌표를 저장하기 위해 Class 를 만들어 사용했다.

import java.io.*;
import java.util.*;

public class Main {
	static int width;
	static int height;

	static class Pair {
		int x, y;

		Pair(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}

	public static void main(String[] args) throws IOException {

		Scanner scan = new Scanner(System.in);

		width = scan.nextInt();
		height = scan.nextInt();

		int N = scan.nextInt();
		Pair[] arr = new Pair[N];

		for (int i = 0; i < N; i++) {
			int num1 = scan.nextInt();
			int num2 = scan.nextInt();

			arr[i] = changeToCoodinate(num1, num2);
		}

		int dong_x = scan.nextInt();
		int dong_y = scan.nextInt();

		Pair dong_pair = changeToCoodinate(dong_x, dong_y);

		int sum = 0;

		for (Pair pair : arr) {
			sum += findShortestPath(dong_pair.x, dong_pair.y, pair.x, pair.y);
		}

		System.out.println(sum);

		scan.close();
	}

	static Pair changeToCoodinate(int x, int y) {

		if (x == 1) {
			x = y;
			y = height;
		} else if (x == 2) {
			x = y;
			y = 0;
		} else if (x == 3) {
			x = 0;
			y = height - y;
		} else {
			x = width;
			y = height - y;
		}

		Pair pair = new Pair(x, y);

		return pair;

	}

	static int findShortestPath(int dong_x, int dong_y, int x, int y) {

		int distance_x = 0;
		int distance_y = 0;
		if (dong_x == x) {
			distance_y = Math.abs(dong_y - y);
		} else {
			distance_y = Math.min(Math.abs(dong_y + y), Math.abs(height * 2 - (dong_y + y)));
		}
		if (dong_y == y) {
			distance_x = Math.abs(dong_x - x);
		} else {
			distance_x = Math.min(Math.abs(dong_x + x), Math.abs(width * 2 - (dong_x + x)));
		}
		return distance_x + distance_y;
	}

}

 

[참고자료]

https://lemonlemon.tistory.com/142

728x90
Comments