😈 알고리즘/💻 백준

💻 2556번 문제 : 최댓값 ➕

Buᐢ༝ᐢy 2022. 11. 19. 06:00
2566번: 최댓값
3 23 85 34 17 74 25 52 65 10 7 39 42 88 52 14 72 63 87 42 18 78 53 45 18 84 53 34 28 64 85 12 16 75 36 55 21 77 45 35 28 75 90 76 1 25 87 65 15 28 11 37 28 74 65 27 75 41 7 89 78 64 39 47 47 70 45 23 65 3 41 44 87 13 82 38 31 12 29 29 80
https://www.acmicpc.net/problem/2566
#include <iostream>
using namespace std;

int main()
{
	int array[9][9] = {};
	int row = 1;
	int column = 1;
	int max = 0;

	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			cin >> array[i][j];
			if (max < array[i][j])
			{
				max = array[i][j];
				row = i+1;
				column = j+1;
			}
		}
	}
	cout << max << '\n' << row << ' ' << column << '\n';
}
메모리 (KB)시간 (ms)코드 길이 (B)
20200367

➕ 재풀이

#include <iostream>
using namespace std;

int main()
{
	int array[9][9] = {};
	int row = 0;
	int column = 0;
	int max = 0;

	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			cin >> array[i][j];
			if (max < array[i][j])
			{
				max = array[i][j];
				row = i+1;
				column = j+1;
			}
		}
	}

	cout << max << '\n' << row << ' ' << column << '\n';
}

이 문제는 100%까지 갔었음에도 계속 틀렸던 문제였다. 질문들을 보니 다 비슷한 케이스였는데, 0만 들어있는 예시를 보아도 처음에는 사실 이해가 어려웠다.

Ideone.com
Ideone is something more than a pastebin; it's an online compiler and debugging tool which allows to compile and run code online in more than 40 programming languages.
https://ideone.com/ERw3v6

어떤 분이 0만 들어가 있는 예시를 만들어주셨다. 여기서 주목해야 할 점은 row, column이 초기화 되지 않아 출력값이 쓰레기값이 들어가있다는 점이다.

그렇다면 나는 0으로 초기화를 해주었는데 왜 틀렸던걸까?

문제를 보면 쉽게 알 수 있다. 코딩을 하는 입장에서 웬만한 int형 변수의 초기화 값이나 인덱스 번호의 1번은 0이라서 0으로 초기화를 해주었기에 또 틀렸던 것이다. 위 이미지를 보면 행과 열의 첫 번째 수는 0이 아닌 1이기 때문이다. 그래서 row, column 변수들을 초기화할 때 0이 아닌 1로 해주면 문제는 쉽게 해결된다.


Uploaded by N2T