상하좌우 움직이는 함수 만들어서 통과했는데 이건 아니다 싶어서 검색해보니
대부분 dx, dy를 사용했더라.
왜 이걸 생각을 못했을까... 에바네 ㄹㅇ
dx dy 사용
#include <iostream>
int snail[11][11];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
void init() {
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
snail[i][j] = 0;
}
}
}
void fill_arr(int n) {
int x = 0, y = 0, dir = 0;
snail[0][0] = 1;
int cnt = 2;
while(cnt <= n * n) {
int nx = x + dx[dir];
int ny = y + dy[dir];
if (snail[nx][ny] != 0 || nx < 0 || nx > n - 1 || ny < 0 || ny > n - 1) {
dir++;
dir %= 4;
continue;
}
snail[nx][ny] = cnt;
x = nx;
y = ny;
cnt++;
}
}
int main() {
int tc = 0;
std::cin >> tc;
for (int i = 1; i < tc + 1; i++) {
int n = 0;
std::cin >> n;
init();
fill_arr(n);
std::cout << "#" << i << "\n";
for (int j = 0; j < n; j++) {
for(int k = 0; k < n; k++) {
std::cout << snail[j][k] << " ";
}
std::cout << "\n";
}
}
return 0;
}
처음 통과했던 코드
#include <iostream>
int snail[11][11];
void right(int x, int y, int start, int n);
void left(int x, int y, int start, int n);
void down(int x, int y, int start, int n);
void up(int x, int y, int start, int n);
bool check(int cnt, int n) {
return cnt > n * n;
}
void left(int x, int y, int start, int n) {
int nx = x, ny = y - 1, cnt = start;
while (snail[nx][ny] == 0) {
if (ny < 0) {
break;
}
snail[nx][ny] = cnt;
ny--;
cnt++;
}
if (check(cnt, n)) {
return;
}
up(nx, ny + 1, cnt, n);
}
void down(int x, int y, int start, int n) {
int nx = x + 1, ny = y, cnt = start;
while (snail[nx][ny] == 0) {
if (nx > n - 1) {
break;
}
snail[nx][ny] = cnt;
nx++;
cnt++;
}
if (check(cnt, n)) {
return;
}
left(nx - 1, ny, cnt, n);
}
void right(int x, int y, int start, int n) {
int nx = x, ny = y + 1, cnt = start;
while (snail[nx][ny] == 0) {
if (ny > n - 1) {
break;
}
snail[nx][ny] = cnt;
ny++;
cnt++;
}
if (check(cnt, n)) {
return;
}
down(nx, ny - 1, cnt, n);
}
void up(int x, int y, int start, int n) {
int nx = x - 1, ny = y, cnt = start;
while (snail[nx][ny] == 0) {
if (nx < 0) {
break;
}
snail[nx][ny] = cnt;
nx--;
cnt++;
}
if (check(cnt, n)) {
return;
}
right(nx + 1, ny, cnt, n);
}
void init() {
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
snail[i][j] = 0;
}
}
}
int main() {
int tc = 0;
std::cin >> tc;
for (int i = 1; i < tc + 1; i++) {
int n = 0;
std::cin >> n;
init();
snail[0][0] = 1;
right(0, 0, 2, n);
std::cout << "#" << i << "\n";
for (int j = 0; j < n; j++) {
for(int k = 0; k < n; k++) {
std::cout << snail[j][k] << " ";
}
std::cout << "\n";
}
}
return 0;
}
'PS > SWEA' 카테고리의 다른 글
SWEA 1215 : [S/W 문제해결 기본] 3일차 - 회문1 [C++] (0) | 2023.01.13 |
---|---|
SWEA 1206 : [S/W 문제해결 기본] 1일차 - View [C++] (0) | 2022.11.17 |
SWEA 1926 : 간단한 369게임 (0) | 2022.11.17 |
SWEA 1204 : [S/W 문제해결 기본] 1일차 - 최빈수 구하기 [C++] (0) | 2022.11.17 |
SWEA 1859 : 백만 장자 프로젝트 [C++] (0) | 2022.11.16 |