231019 행렬과 연산

Jongleee·2023년 10월 19일
0

TIL

목록 보기
394/737
private int numRows;
private int numCols;
private ArrayDeque<Integer> leftCol;
private ArrayDeque<Integer> rightCol;
private ArrayDeque<ArrayDeque<Integer>> middleRows;

public int[][] solution(int[][] rc, String[] operations) {
	initialize(rc);

	for (String op : operations) {
		if (op.charAt(0) == 'R') {
			rotate();
		}
		if (op.charAt(0) == 'S') {
			shiftRow();
		}
	}

	return getSolution();
}

private void initialize(int[][] rc) {
	numRows = rc.length;
	numCols = rc[0].length;

	leftCol = new ArrayDeque<>();
	rightCol = new ArrayDeque<>();
	middleRows = new ArrayDeque<>();

	for (int i = 0; i < numRows; i++) {
		leftCol.add(rc[i][0]);
		rightCol.add(rc[i][numCols - 1]);

		ArrayDeque<Integer> tmp = new ArrayDeque<>();
		for (int j = 1; j < numCols - 1; j++) {
			tmp.add(rc[i][j]);
		}
		middleRows.add(tmp);
	}
}

private int[][] getSolution() {
	int[][] ans = new int[numRows][numCols];
	for (int i = 0; i < numRows; i++) {
		ans[i][0] = leftCol.pollFirst();
		ans[i][numCols - 1] = rightCol.pollFirst();
	}

	int i = 0;
	for (ArrayDeque<Integer> row : middleRows) {
		for (int j = 1; j < numCols - 1; j++) {
			ans[i][j] = row.pollFirst();
		}
		i++;
	}
	return ans;
}

private void rotate() {
	if (numCols == 2) {
		rightCol.addFirst(leftCol.pollFirst());
		leftCol.addLast(rightCol.pollLast());
		return;
	}

	ArrayDeque<Integer> firstRow = middleRows.peekFirst();
	ArrayDeque<Integer> lastRow = middleRows.peekLast();

	firstRow.addFirst(leftCol.pollFirst());
	rightCol.addFirst(firstRow.pollLast());

	lastRow.addLast(rightCol.pollLast());
	leftCol.addLast(lastRow.pollFirst());
}

private void shiftRow() {
	ArrayDeque<Integer> firstRow = middleRows.pollLast();
	leftCol.addFirst(leftCol.pollLast());
	rightCol.addFirst(rightCol.pollLast());
	middleRows.addFirst(firstRow);
}

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

0개의 댓글