printf("%c의 블로그", 'Molkka');

코딩테스트/백준

[13413번] 오셀로 재배치

mol_kka 2022. 3. 24. 17:27

>> 문제 보러 가기

https://www.acmicpc.net/problem/13413

 

13413번: 오셀로 재배치

로봇을 좋아하는 세희는 로봇동아리에서 카메라와 센서, 라즈베리 파이, 집게발을 이용해 로봇을 완성하였다. 이 로봇을 통해서 오셀로 재배치라는 작업을 하려고 한다. 오셀로 말은 앞면이 검

www.acmicpc.net

 

 

>> 문제 풀이

 

1) 사용자 입력 구현

int testDataNum = scan.nextInt(); // 테스트를 몇 번 할건지 저장하는 변수
int[] result = new int[testDataNum]; //결과를 저장하는 변수
for (int i = 0; i < testDataNum; i++) {
	int pieces = scan.nextInt(); // 오셀로 말의 개수
	String initialState = scan.next(); // 처음 배치 상태, W,B로 설정
	String targetState = scan.next(); // 최종 배치 상태, W,B로 설정
	result[i] = calc(pieces, initialState, targetState); //결과를 계산하는 calc()함수
}

 

2) 오셀로 시스템 기능 구현

public static int calc(int pieces, String initialState, String targetState) {
		int result = 0;
		char[] initialStateList = charAt(initialState);
		char[] targetStateList = charAt(targetState);
		int initialStateWhiteNum = howMuchWhite(initialStateList);
		int targetStateWhiteNum = howMuchWhite(targetStateList);
		int difference = Math.abs(targetStateWhiteNum - initialStateWhiteNum);
		// 2번 활동
		if (initialStateWhiteNum != targetStateWhiteNum) {
			if (initialStateWhiteNum > targetStateWhiteNum) {
				// WtoB
				for (int i = 0; i < pieces; i++) {
					if (difference == result)
						break;
					if (targetStateList[i] == 'B' && initialStateList[i] == 'W') {
						initialStateList[i] = 'B';
						result++;
					}
				}
			} else if (initialStateWhiteNum < targetStateWhiteNum) {
				// BtoW
				for (int i = 0; i < pieces; i++) {
					if (difference == result)
						break;
					if (targetStateList[i] == 'W' && initialStateList[i] == 'B') {
						initialStateList[i] = 'W';
						result++;
					}
				}
			}
		}
		// 1번 활동, 옮기는 횟수만 구함
		int changeNum = 0;
		for (int i = 0; i < pieces; i++) {
			if (initialStateList[i] != targetStateList[i]) {
				changeNum++;
			}
		}
        
		result += changeNum / 2;
		return result;
	}

 

 

회고//

 

2번 기능 구현 내용 중, if문 조건을 다는 부분을 처음에는

howMuchWhite(initialStateList) > howMuchWhite(targetStateList);

이런 식으로 함수로 설정했다.

그랬더니 시간이 오래 걸린다고 통과되지 않았다.

 

컴퓨터는 빠르니까 간단한 함수 한 번 돌리는 게 무슨 대수일까 생각했는데,

효율적인 코드를 고민하는 방향성이 있는 태도가 중요하다는 걸 알게 되었다.

'코딩테스트 > 백준' 카테고리의 다른 글

[10951번] A + B - 4 (백준)  (0) 2022.05.03