📊알고리즘/이론
배열 채우기 알고리즘
meteorfish
2023. 3. 11. 15:19
728x90
지그재그 배열
https://codeup.kr/problem.php?id=1503
[ 출력 ]
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
배열 사용 안하기
더보기
#include <stdio.h>
int main()
{
int n,idx = 1;
scanf("%d", &n);
int i=0;
int chk = 1;
while (idx <= n*n) {
if (chk % 2==1) {
for (i=idx; i < idx + n; i++) {
printf("%d ", i);
}
idx = i;
}
else {
for (i = idx + n-1; i >= idx; i--) {
printf("%d ", i);
}
idx += n;
}
chk++;
printf("\n");
}
return 0;
}
지그재그 배열2
[ 출력 ]
1 6 7
2 5 8
3 4 9
더보기
#include <stdio.h>
int main()
{
int n, m, idx = 1;
int arr[101][101] = { 0, };
scanf("%d", &n);
int i=0;
int chk = 1;
while (idx <= n*n) {
if (chk % 2 == 1) {
for (int i = 0; i < n; i++) {
arr[i][chk - 1] = idx++;
}
}
else {
for (int i = n-1; i >= 0; i--) {
arr[i][chk - 1] = idx++;
}
}
chk++;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
2차원 배열 채우기 3(달팽이 배열)
[ 출력 ]
1 2 3
8 9 4
7 6 5
왼쪽 -> 아래 -> 오른쪽 -> 위
순서대로 반복된다.
이때 중요한 것이 꺾어지는 지점을 중복되지 않게 하는 것이 중요하다.
예를 들어)
왼쪽으로 가는 반복문에 3을 포함했으면, 아래쪽으로 가는 반복문은 y+1한 지점부터 해야한다.
만약 위 방법대로 진행하려면
x값을 미리 더한 후에 배열에 값을 입력해야함
왜냐하면,
더보기
#include <stdio.h>
int main()
{
int n, m, idx = 2;
int arr[101][101] = { 0, };
scanf("%d", &n);
int x=0,y=0;
arr[0][0] = 1;
while (idx <= n*n) {
// 오른쪽
while (x+1 < n && arr[y][x+1] == 0) {
x++;
arr[y][x] = idx++;
}
// 아래
while (y+1 <n && arr[y+1][x] == 0) {
y++;
arr[y][x] = idx++;
}
// 왼쪽
while(x-1 >= 0&& arr[y][x-1] == 0) {
x--;
arr[y][x] = idx++;
}
//위
while (y-1 >=0 && arr[y-1][x] == 0) {
y--;
arr[y][x] = idx++;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
728x90