프로그래머스
양의 정수
n이 매개변수로 주어집니다.n×n배열에 1부터 까지 정수를 인덱스 [0][0]부터 시계방향 나선형으로 배치한 이차원 배열을 return 하는 solution 함수를 작성해 주세요.
제한사항
입출력 예
| n | result |
|---|---|
| 4 | [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]] |
| 5 | [[1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9]] |
using System;
public class Solution {
public Func<int,int,int,int[,],bool> checkRight = (x, y, n, m) => x + 1 < n && m[y, x + 1] == 0;
public Func<int,int,int,int[,],bool> checkDown = (x, y, n, m) => y + 1 < n && m[y + 1, x] == 0;
public Func<int,int,int,int[,],bool> checkLeft = (x, y, n, m) => x - 1 >= 0 && m[y, x - 1] == 0;
public Func<int,int,int,int[,],bool> checkUp = (x, y, n, m) => y - 1 >= 0 && m[y - 1, x] == 0;
public char MoveRight(ref int x, ref int y, int[,] metrix, int n)
{
if (checkRight(x, y, n, metrix))
{
x++;
return 'd';
}
if (checkDown(x, y, n, metrix))
{
y++;
return 's';
}
if (checkLeft(x, y, n, metrix))
{
x--;
return 'a';
}
if (checkUp(x, y, n, metrix))
{
y--;
return 'w';
}
return 'd';
}
public char MoveDown(ref int x, ref int y, int[,] metrix, int n)
{
if (checkDown(x, y, n, metrix))
{
y++;
return 's';
}
if (checkLeft(x, y, n, metrix))
{
x--;
return 'a';
}
if (checkUp(x, y, n, metrix))
{
y--;
return 'w';
}
if (checkRight(x, y, n, metrix))
{
x++;
return 'd';
}
return 'd';
}
public char MoveLeft(ref int x, ref int y, int[,] metrix, int n)
{
if (checkLeft(x, y, n, metrix))
{
x--;
return 'a';
}
if (checkUp(x, y, n, metrix))
{
y--;
return 'w';
}
if (checkRight(x, y, n, metrix))
{
x++;
return 'd';
}
if (checkDown(x, y, n, metrix))
{
y++;
return 's';
}
return 'd';
}
public char MoveUp(ref int x, ref int y, int[,] metrix, int n)
{
if (checkUp(x, y, n, metrix))
{
y--;
return 'w';
}
if (checkRight(x, y, n, metrix))
{
x++;
return 'd';
}
if (checkDown(x, y, n, metrix))
{
y++;
return 's';
}
if (checkLeft(x, y, n, metrix))
{
x--;
return 'a';
}
return 'd';
}
public int[,] solution(int n) {
int[,] metrix = new int[n, n];
int x = 0;
int y = 0;
char curDirection = 'd';
for (int i = 1; i <= n * n; i++)
{
metrix[y, x] = i;
switch (curDirection)
{
case 'd':
curDirection = MoveRight(ref x, ref y, metrix, n);
break;
case 's':
curDirection = MoveDown(ref x, ref y, metrix, n);
break;
case 'a':
curDirection = MoveLeft(ref x, ref y, metrix, n);
break;
case 'w':
curDirection = MoveUp(ref x, ref y, metrix, n);
break;
}
}
return metrix;
}
}
정확성: 100.0
합계: 100.0 / 100.0
아니.. 갑자기 어려운 문제 뭔데? ㅋㅋㅋ
코드를 조금 더 간단히 할 수 있는 방법이 있을 것 같긴 한데 지금 당장은 잘 생각이 나지 않는다.
다른 사람 풀이는 접근 방법 자체는 크게 다르지 않은 사람이 대부분 이었다.
다만 유독 한 사람의 풀이가 신기했다.