본문 바로가기
전공공부/코딩테스트

(c++) SWEA "1954) 달팽이 숫자"

by 시아나 2022. 5. 25.

https://swexpertacademy.com/main/code/problem/problemSolver.do?contestProbId=AV5PobmqAPoDFAUq 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com


#include <iostream>
#include <vector>
using namespace std;

void solution(int N) {
	int num = 1;
	int level = 0;
	vector<vector<int>> list;
	for (int i = 0; i < N; i++) {
		vector<int> tmp(N, 0);
		list.push_back(tmp);
	}
	if (N == 1) {
		cout << num << endl;
		return;
	}
	while (num <= N * N) {
		int minus = 2 * level;
		for (int i = 0; i < N -1 - minus && num <=N*N; i++) {
			list[level][level + i] = num++;
		}
		for (int i = 0; i < N - 1 - minus && num <= N * N; i++) {
			list[level+i][N-1-level] = num++;
		}
		for (int i = N-1; i > minus && num <= N * N; i--) {
			list[N-1-level][i-level] = num++;
		}
		for (int i = N-1; i >minus && num <= N * N; i--) {
			list[i-level][level] = num++;
		}
		level++;
		if (N % 2 == 1 && level == N / 2) {
			list[N / 2][N / 2] = num++;
		}
	}
	for (int i = 0; i < N; i++) {
		for (int n : list[i]) {
			cout << n << " ";
		}
		cout << endl;
	}
}

int main() {
	int T; cin >> T;
	for (int i = 1; i <= T; i++) {
		int n; cin >> n;
		cout << "#" << i << endl;
		solution(n);
	}
	return 0;
}