티스토리 뷰
spiral (II.cpp)
문제
1 부터 나선 형 모양으로 배열에 값을 넣은 후 출력하는 프로그램을 작성하시오.
입력
입력은 배열의 크기 n 이 주어진다. n * n 행 배열이다. ( 3 <= n <= 25)
출력
각 숫자 사이 한 칸의 공백을 가지고 나선형(달팽이) 배열을 출력한다.
예제 입력
3
예제 출력
1 2 3
8 9 4
7 6 5
예제 입력
6
예제 출력
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
//코드
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//총 몇개의 숫자를 입력 받을 것인지
int a = 0;
// int b = 0;
// int c = 0;
a = sc.nextInt();
// b = sc.nextInt();
// c = sc.nextInt();
int[][] box = new int[a+1][a+1];
//direction 이 1일 땐 가로이동 / 0일때는 세로 이동
int right_direction = 1;
int bottom_direction = 0;
int right = 0;
int bottom = 1;
for(int i = 1 ; i <= a*a ; i++) {
if(right_direction == 1 && bottom_direction == 0) {
if(right+right_direction > a || box[right+right_direction][bottom] != 0) {
right_direction = 0; bottom_direction = 1;
}
}else if(right_direction == 0 && bottom_direction == 1) {
if(bottom+bottom_direction > a || box[right+right_direction][bottom+bottom_direction] != 0) {
right_direction = -1; bottom_direction = 0;
}
}else if(right_direction == -1 && bottom_direction == 0) {
if(right+right_direction < 1 || box[right+right_direction][bottom+bottom_direction] != 0) {
right_direction = 0; bottom_direction = -1;
}
}else if(right_direction == 0 && bottom_direction == -1) {
if(bottom+bottom_direction < 1 || box[right+right_direction][bottom+bottom_direction] != 0) {
right_direction = 1; bottom_direction = 0;
}
}
right = right+right_direction;
bottom = bottom+bottom_direction;
box[right][bottom] = i;
}
for(int i = 1 ; i<= a ; i++) {
for(int j = 1 ; j <= a; j++) {
System.out.print(box[j][i]+" ");
}
System.out.println("");
}
}
}
'알고리즘 문제 풀이 ' 카테고리의 다른 글
부등호 (0) | 2018.09.20 |
---|---|
좋은 수열 찾기 (0) | 2018.09.18 |
이진 트리 순회 (0) | 2018.09.18 |
소들의 줄세우기 (0) | 2018.09.18 |
자연수의 합 / Division (0) | 2018.09.17 |
단지번호 붙이기 (0) | 2018.09.17 |
백준 스택 수열 1874번 (0) | 2018.07.03 |
weird (0) | 2018.07.01 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- react
- java #알고리즘 #백준
- npm
- java #백준 #알고리즘 #2805 #나무자르기
- Terminal
- 알고리즘
- 쿼드트리
- Game
- java #알고리즘 #백준 #퇴사
- java #하노이 #알고리즘 #백준
- javascript #백준 #회의실배정 #알고리즘
- 1992번
- java #알고리즘 #백준 #패션왕신해빈
- 색종이자르기
- javascript #백준 #알고리즘 #LCS
- webspider
- 백준 #알고리즘 #전깃줄 #NodeJs #javascript
- java #알고리즘 #백준 #N과M #백트래킹
- 백준 #java #알고리즘
- javascript #연속합 #알고리즘 #백준
- Javascript
- 한글 자동 완성
- 백준
- TypeScript
- 중간거리 #야만나 #약속장소추천 #중간위치 #웹 #리액트 #React #reactjs #kakao지도 #kakaoapi
- java #오르막수 #백준 #알고리즘
- webpack
- 2630번
- java #백준 #알고리즘 #로또 #6603
- java #퀵소트 #quicksort #알고리즘 #백준
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함