
내가 생각했을때 문제에서 원하는부분
The first line of the input will be the (x,y) intersection that you are waiting at for a taxi.
The second line has a single integer N (1<=N<=100) of the number of available taxis in Manhattan.
The next N lines will be the (x,y) positions of taxis around Manhattan.
Taxis will always be at the intersections of streets and there will only be one taxi per intersection.
All taxis will be at different manhattan distances from you.
The position of the closest taxi to you.
내가 이 문제를 보고 생각해본 부분
BufferedReader로 빠르게 입력을 받는다.
첫 줄을 읽고 공백 기준으로 나누어 대기 위치 (X, Y)를 저장한다.
두 번째 줄은 택시 대수 N을 정수로 변환해 저장한다.
minDistance를 아주 큰 값(Integer.MAX_VALUE)으로 초기화 하여 비교할 준비를 한다.
반복문을 돌면서 각 택시 위치를 읽고, 맨해튼 거리 계산을 한다.
계산한 거리가 현재 최소 거리보다 작으면, 최소거리를 갱신하고 그 택시 위치를 기록한다.
최종적으로 최소 거리 택시의 위치를 출력한다.
코드로 구현
package baekjoon.baekjoon_34;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// 백준 13221번 문제
public class Main1354 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 1. 대기 위치 입력받기
String[] input = br.readLine().split(" ");
int X = Integer.parseInt(input[0]);
int Y = Integer.parseInt(input[1]);
// 2. 택시 대수 입력받기
int N = Integer.parseInt(br.readLine());
// 가장 가까운 택시 위치와 현재 최소 거리 초기화
int minDistance = Integer.MAX_VALUE;
int closestX = -1;
int closestY = -1;
// 3. 각 택시 위치와 거리 계산, 최소 거리 갱신
for (int i = 0; i < N; i++) {
String[] taxiPos = br.readLine().split(" ");
int tx = Integer.parseInt(taxiPos[0]);
int ty = Integer.parseInt(taxiPos[1]);
int dist = Math.abs(X - tx) + Math.abs(Y - ty);
if (dist < minDistance) {
minDistance = dist;
closestX = tx;
closestY = ty;
}
}
// 4. 가장 가까운 택시 위치 출력
System.out.println(closestX + " " + closestY);
br.close();
}
}
코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.