Created
December 4, 2015 07:44
-
-
Save hyeonsupark/2a76310abba42d286153 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ideone | |
{ | |
public static void main (String[] args) throws java.lang.Exception | |
{ | |
Scanner scanner = new Scanner(System.in); | |
int variable = -1; | |
int n = scanner.nextInt(); | |
int[][] arr = new int[n][n]; | |
int temp = n * n; | |
int x = n - 1; | |
int y = n; | |
int cnt = 1; | |
for(int i = 0; i < n; i++) { | |
for(int j = 0; j < n; j++) { | |
arr[j][i] = cnt; | |
cnt += 1; | |
} | |
} | |
while(n >= 0) { | |
for(int i = 0; i < n; i++) { | |
y += variable; | |
System.out.print(arr[x][y] + " "); | |
} | |
n -= 1; | |
for(int i = 0; i < n; i++) { | |
x += variable; | |
System.out.print(arr[x][y] + " "); | |
} | |
variable *= -1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
사이냅 소프트 신입 공채 퀴즈에 있던 문제..
일단 보아하니 달팽이 배열을 거꾸로? 돌려 놓은 느낌이었다.
처음에는 종이에 이차원 배열 인덱스를 적어보면서 무슨 규칙이 있나 열심히 들여다 봤다..
뭔가 보다보니 이중 loop로 해결을 안봐도 될거 같았지만 결국 while문 안에 for문 두개가 있는 코드가 됐다.
규칙은 간단했다
열 -> 행 -> 열 -> 행을 기준으로 돌고 적절한 증가와 감소..
4 x 4 배열을 기준으로
첫번째 loop는 4번 돌고, y값이 감소 (16 12 8 4)
두번째 loop는 3번 돌고, x값이 감소 (3 2 1)
세번째 loop는 3번 돌고, y값이 증가 (5 9 13)
네번째 loop는 2번 돌고, x값이 증가 (14 15)
다섯번째 loop는 2번 돌고, y값이 감소 (11 7)
여섯번째 loop는 1번 돌고, x값이 감소(6)
일곱번째 loop는 1번 돌고 y값이 증가하나 끝
일단 보면 처음에 y값이 감소해야하니
variable
변수를 -1로 둬서 감소되게한다.다음 행을 건드는 루프는 3번 돌아야하니
n
에서 1을 빼주고x
는 (0, 3)에서 감소하므로 처음 초기값이n
에서 1을 빼준 값이다.다음은 증가하는 부분이니
variable
에 -1을 곱해주며 양수로 바꿔주고적절한 증가와 감소를 하게한다.