행렬테두리 회전하기

Falcon·2021년 10월 23일
1

programmers

목록 보기
21/27

🔒 문제

🧠 생각의 흐름

  • 순서대로 회전해야함
  • 회전을 하지 않는 케이스도 있을 수 있다.
    (ex. 3,3 3,3 같은 같은 좌표 제시)
  • 굳이 모든 테두리 원소를 정렬할 필요가 없이 최소값만 찾으면 됨.

=> 테두리 범위를 좌표로 정의하면 이렇다.
시작점 : (x1x_1, y1y_1), 끝점: (x2x_2, y2y_2) 이라고 하면

1. 테두리 좌표 범위 대수 표현

상단 가로줄: (x1x_1 ~ x2x_2, y1y_1)
우단 세로줄: (x2x_2, y1y_1 ~ y2y_2)
하단 가로줄: (x1x_1 ~ x2x_2, y2y_2)
좌단 세로줄: (x1x_1, y1y_1 ~ y2y_2)

2. 회전

  1. 시작점의 좌표 저장

  2. round 1-> 2-> 3-> 4 순으로 회전

  3. 킵했던 시작점 좌표를 한칸 이동한 곳에 삽입.

매 라운드를 돌 때마다 해당 점의 값을 최소값과 비교하여 가장 작은 값을 return (테두리 원소중 가장 작은값 return)

🔑 풀이 (Go)

func rotate(startRow, startCol, endRow, endCol int, matrix [][]int) int {

	// round 1,2,3,4 4가지
	var startValue int = matrix[startRow][startCol]
	min := startValue

	// round1
	for rowIdx := startRow; rowIdx < endRow; rowIdx++ {
		matrix[rowIdx][startCol] = matrix[rowIdx + 1][startCol]
		if min > matrix[rowIdx][startCol] {
			min = matrix[rowIdx][startCol]
		}
	}

	// round2
	for colIdx := startCol; colIdx < endCol; colIdx++ {
		matrix[endRow][colIdx] = matrix[endRow][colIdx + 1]

		if min > matrix[endRow][colIdx] {
			min = matrix[endRow][colIdx]
		}
	}

	// round3
	for rowIdx := endRow; rowIdx > startRow; rowIdx-- {
		matrix[rowIdx][endCol] = matrix[rowIdx - 1][endCol]

		if min > matrix[rowIdx][endCol] {
			min = matrix[rowIdx][endCol]
		}
	}

	// round4
	for colIdx := endCol; colIdx > startCol; colIdx-- {
		matrix[startRow][colIdx] = matrix[startRow][colIdx - 1]

		if min > matrix[startRow][colIdx] {
			min = matrix[startRow][colIdx]
		}
	}

	// start value 위치 옮기기
	if startCol < endCol {
		matrix[startRow][startCol + 1] = startValue
	}

	return min
}

func solution(rows int, columns int, queries [][]int) []int {
	// 맨 첫 가로, 세로줄은 편의상 비워둠.

	answerLength := len(queries)
	answer := make([]int, answerLength)

	matrix := make([][]int, rows + 1)
	for rowIdx := 1; rowIdx <= rows; rowIdx++ {
		matrix[rowIdx] = make([]int, columns + 1)
	}


	// initialize the matrix
	num := 0
	for rowIndex := 1; rowIndex <= rows; rowIndex++ {
		for colIndex := 1; colIndex <= columns; colIndex++ {
			num++
			matrix[rowIndex][colIndex] = num
		}
	}

	// 시작 ~ 종료 좌표
	// 반시계 방향으로 돌며 위치 옮기기 (4줄)
	// 회전 시키기

	for index, point := range queries {
		// x1, y1, x2, y2
		min := rotate(point[0], point[1], point[2], point[3], matrix)
		answer[index] = min
	}



	return answer
}

테스트 코드

func Test(testing *testing.T) {
	rows := 100
	columns := 97

	answerArray := []int{1}

	//[[1, 1, 100, 97]]
	queries := [][]int{
							{1, 1, 100, 97},
							//{1, 2, 2, 3},
							//{2, 1, 3, 2},
							//{2, 2, 2, 3},
						}
	resultArray := solution(rows, columns, queries)

	if isSuccess := Equal(answerArray, resultArray); isSuccess {
		fmt.Println("Success!!")
	} else {
		testing.Errorf("Failed to.. %v\n", resultArray)
	}

}

func Equal(a, b []int) bool {
	if len(a) != len(b) {
		return false
	}
	for i, v := range a {
		if v != b[i] {
			return false
		}
	}
	return true
}
profile
I'm still hungry

0개의 댓글