Last active
July 20, 2020 04:35
-
-
Save dalcon10028/afd62e80e9a76988553b5694736e0c97 to your computer and use it in GitHub Desktop.
4주차 스택과 재귀
This file contains hidden or 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
/* | |
------------------------------ | |
| 스택 | | |
------------------------------ | |
*/ | |
#include <stdio.h> | |
#include <string.h> | |
// 사용할 함수들을 선언합니다. | |
void push(int n), menu(); | |
int pop(), size(), empty(), top(); | |
// 배열을 이용한 스택이므로 전역변수 배열 선언 | |
int stack[10001]; | |
int idx = -1; // 현재 스택에서 가장 위(top)을 가리키는 인덱스 | |
int main(){ | |
int input; | |
scanf("%d", &input); | |
for(int i=0; i<input; i++) menu(); | |
} | |
void menu(){ | |
char str[6]; // 제일 긴 문자열이 empty 5글자이므로 null문자까지 포함해서 6개의 char가 필요합니다 | |
int num; | |
scanf("%s", str); | |
if(strcmp(str, "push")==0){ | |
scanf("%d", &num); | |
push(num); | |
}else if(strcmp(str, "pop")==0) | |
printf("%d\n", pop()); | |
else if(strcmp(str, "size")==0) | |
printf("%d\n", size()); | |
else if(strcmp(str, "empty")==0) | |
printf("%d\n", empty()); | |
else if(strcmp(str, "top")==0) | |
printf("%d\n", top()); | |
} | |
void push(int n){ | |
// 현재 제일 위를 가리키는 인덱스를 1 증가시킨후 새로운 값을 대입 | |
stack[++idx] = n; | |
} | |
int pop(){ | |
// 스택이 비어있으면 -1을 반환 | |
if(empty()) return -1; | |
// 아닐 경우는 인덱스를 하나 낮추기 --> 어차피 새로운 값을 추가하면 덮어 씌워지면서 지워지기 때문에 | |
return stack[idx--]; | |
} | |
int size(){ | |
// 스택의 크기는 현재 인덱스+1 | |
return idx+1; | |
} | |
int empty(){ | |
// 현재 제일 위를 가리키는 인덱스가 -1이면 1 아니면 0 반환 | |
return idx==-1 ? 1 : 0; | |
} | |
int top(){ | |
// 스택이 비어있으면 -1 아니면 현재 제일 위의 값을 반환 | |
return empty() ? -1 : stack[idx]; | |
} | |
/* ------------------------------------ | |
// 재귀 (별 찍기 - 10 ) | |
------------------------------------------*/ | |
#include <stdio.h> | |
// 판을 모두 0으로 초기화 | |
int field[6562][6562] = {{0,}}; | |
void star(); | |
int main(){ | |
int input; | |
scanf("%d", &input); | |
// 재귀함수의 실행 | |
star(input, 0, 0); | |
// 입력값(input)의 크기 만큼 읽으면서 0은 공백 1은 별을 찍습니다. | |
for(int i=0; i<input; i++){ | |
for(int j=0; j<input; j++) | |
printf("%c",field[i][j]==0 ? ' ' : '*'); | |
printf("\n"); | |
} | |
} | |
void star(int size, int x, int y){ | |
// 무한으로 재귀가 일어나지 않도록 끝나는 지점을 정해줍니다. | |
if(size==1) { | |
// 크기가 1까지 작아지면 해당 값은 1(별)로 지정 | |
field[y][x] = 1; | |
return; // 그리고 함수 종료 | |
} | |
// 좌표를 해당 위치로 보냅니다. | |
star(size/3, x, y); // 좌상 | |
star(size/3, x+size/3, y); // 상 | |
star(size/3, x+size/3*2, y); // 우상 | |
star(size/3, x, y+size/3); // 좌 | |
star(size/3, x+size/3*2, y+size/3); // 우 | |
star(size/3, x, y+size/3*2); // 좌하 | |
star(size/3, x+size/3, y+size/3*2); // 하 | |
star(size/3, x+size/3*2, y+size/3*2); // 우하 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment