728x90
정수를 나선형으로 배치하기
class Solution {
val dir = arrayOf(
arrayOf(0, 1, 0, -1),
arrayOf(1, 0, -1, 0)
)
fun solution(n: Int): Array<IntArray> {
var answer: Array<IntArray> = arrayOf()
for (i in 0 until n) {
answer += IntArray(n)
}
var cnt = 1;
var dirIdx = 0;
var x = 0
var y = 0
while (cnt <= n * n) {
while (!(x < 0 || x >= n || y < 0 || y >= n) && answer[x][y] == 0) {
answer[x][y] = cnt++
x += dir[0][dirIdx]
y += dir[1][dirIdx]
}
x -= dir[0][dirIdx]
y -= dir[1][dirIdx]
dirIdx++
if (dirIdx % 4 == 0) {
dirIdx = 0
}
x += dir[0][dirIdx]
y += dir[1][dirIdx]
}
return answer
}
}
특별한 이차원 배열 2
class Solution {
fun solution(arr: Array<IntArray>): Int {
for (i in 0 until arr.size){
for (j in 0 until arr.size){
if (arr[i][j] != arr[j][i])
return 0
}
}
return 1
}
}
정사각형으로 만들기
class Solution {
fun solution(arr: Array<IntArray>): Array<IntArray> {
var answer: Array<IntArray> = arr
for (i in 0 until answer.size){
if (answer.size > answer[i].size){
repeat(answer.size-answer[i].size) {
answer[i] = answer[i].plus(0)
}
}else if (answer.size < answer[i].size){
repeat(answer[i].size-answer.size){
answer = answer.plus(IntArray(answer[i].size,{0}))
}
break
}else break
}
return answer
}
}
이차원 배열 대각선 순회하기
class Solution {
fun solution(board: Array<IntArray>, k: Int): Int {
var sum = 0
for (i in 0 until board.size){
for (j in 0 until board[i].size)
if (i + j <= k) sum += board[i][j]
}
return sum
}
}
728x90