[BaekJoon] 17247번 - 택시 거리 [Java][C++]
[BaekJoon] 17247번 - 택시 거리 [Java][C++]
1. 문제 풀이
두 좌표간 택시거리를 구하는 문제로 택시거리는 $x$ 좌표의 차와 $y$ 좌표의 차의 합이다. 절댓값을 통해 크기의 합을 구해야함에만 주의하면 된다.
2. 코드
1. 풀이 [Java]
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
List<int[]> pos = new ArrayList<>();
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++) {
int x = Integer.parseInt(st.nextToken());
if (x == 1) {
pos.add(new int[]{i, j});
}
}
}
System.out.println(Math.abs(pos.get(0)[0] - pos.get(1)[0]) + Math.abs(pos.get(0)[1] - pos.get(1)[1]));
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<pair<int, int>> pos;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int x;
cin >> x;
if (x == 1) pos.push_back({i, j});
}
}
cout << abs(pos[0].first - pos[1].first) + abs(pos[0].second - pos[1].second);
}
This post is licensed under CC BY 4.0 by the author.