[BaekJoon] #2566 - 최댓값 [Java][C++][Python]
[BaekJoon] #2566 - 최댓값 [Java][C++][Python]
1. 아이디어
9×9 격자에서 최댓값과 그 위치를 찾는 문제다. 칸을 차례로 보며 지금까지의 최댓값보다 큰 수가 나올 때마다 값과 행·열 번호를 함께 갱신하면 되고, 최댓값이 여러 곳이면 그중 어느 위치를 출력해도 되므로 같은 값은 그냥 지나쳐도 괜찮다. 다만 모든 수가 0인 입력에서도 위치가 기록되어야 하므로 최댓값은 0이 아니라 -1에서 시작한다.
2. 코드
풀이 [Java][C++][Python]
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));
int max = -1;
int r = 0, c = 0;
for (int i = 1; i <= 9; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 1; j <= 9; j++) {
int x = Integer.parseInt(st.nextToken());
if (x > max) {
max = x;
r = i;
c = j;
}
}
}
System.out.println(max);
System.out.println(r + " " + c);
}
}
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int mx = -1;
int r = 0, c = 0;
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
int x;
cin >> x;
if (x > mx) {
mx = x;
r = i;
c = j;
}
}
}
cout << mx << '\n';
cout << r << ' ' << c;
}
1
2
3
4
5
6
7
8
9
10
11
12
import sys
input = sys.stdin.readline
mx, r, c = -1, 0, 0
for i in range(1, 10):
for j, x in enumerate(map(int, input().split()), 1):
if x > mx:
mx, r, c = x, i, j
print(mx)
print(r, c)
enumerate의 두 번째 인자로 1을 넘겨 열 번호를 1부터 매겼다.
This post is licensed under CC BY 4.0 by the author.