230918 단체사진 찍기

Jongleee·2023년 9월 18일
0

TIL

목록 보기
367/737
String[] people;
HashMap<Character, Integer> map;
boolean[] visited;
int[] positions;
int count;

public int solution(int n, String[] data) {
	if (data.length != n) {
		return 0;
	}

	people = data;
	map = new HashMap<>();
	visited = new boolean[8];
	positions = new int[8];
	count = 0;

	initializeMap();

	dfs(0);
	return count;
}

public void initializeMap() {
	char[] chars = { 'A', 'C', 'F', 'J', 'M', 'N', 'R', 'T' };
	for (int i = 0; i < chars.length; i++) {
		map.put(chars[i], i);
	}
}

public void dfs(int idx) {
	if (idx == 8) {
		if (isValidArrangement()) {
			count++;
		}
	} else {
		for (int i = 0; i < 8; i++) {
			if (!visited[i]) {
				visited[i] = true;
				positions[idx] = i;
				dfs(idx + 1);
				visited[i] = false;
			}
		}
	}
}

public boolean isValidArrangement() {
	for (String condition : people) {
		int pos1 = positions[map.get(condition.charAt(0))];
		int pos2 = positions[map.get(condition.charAt(2))];
		int distance = condition.charAt(4) - '0' + 1;
		char operator = condition.charAt(3);

		switch (operator) {
			case '=':
				if (Math.abs(pos1 - pos2) != distance) {
					return false;
				}
				break;
			case '>':
				if (Math.abs(pos1 - pos2) <= distance) {
					return false;
				}
				break;
			case '<':
				if (Math.abs(pos1 - pos2) >= distance) {
					return false;
				}
				break;
			default:
				break;
		}
	}
	return true;
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/1835

0개의 댓글