티스토리 뷰

Algorithm

SW Expert Academy_방향 전환

Young_J 2020. 12. 1. 23:13

//알고리즘

1. 단순 구현

2. 시작점의 x,y 좌표와 도착점의 x,y좌표를 비교하여 차이가 더 큰 쪽부터(x or y)시작.

3. 시작점과 도착점이 같을경우 정답은 0 << 예외

더보기
import java.util.Scanner;

public class 방향전환 {
	static int T, X, Y, x, y;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		T = sc.nextInt();

		for (int tc = 1; tc <= T; tc++) {
			X = sc.nextInt();
			Y = sc.nextInt();
			x = sc.nextInt();
			y = sc.nextInt();

			int sX = Math.abs(X - x);
			int sY = Math.abs(Y - y);

			int ans = 0;
			
			if (X == x && Y == y) {
				System.out.printf("#%d %d\n",tc,ans);
				continue;
			}

			if (sX > sY) {
				while (true) {
					ans++;
					if (X - x >= 0) {
						X -= 1;
					} else {
						X += 1;
					}

					// 비교
					if (X == x && Y == y) {
						break;
					}

					ans++;
					if (Y - y >= 0) {
						Y -= 1;
					} else {
						Y += 1;
					}

					if (X == x && Y == y) {
						break;
					}

				}
			} else {

				while (true) {
					ans++;
					if (Y - y >= 0) {
						Y -= 1;
					} else {
						Y += 1;
					}

					if (X == x && Y == y) {
						break;
					}

					ans++;
					if (X - x >= 0) {
						X -= 1;
					} else {
						X += 1;
					}

					// 비교
					if (X == x && Y == y) {
						break;
					}

				}

			}
			
			System.out.printf("#%d %d\n",tc,ans);

		}

	}

}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2025/02   »
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
글 보관함