본문 바로가기

소프트웨어/Algorithm

week2] bfs와 dfs자료

#include<stdio.h>
#include<iostream>
using namespace std;

int arr[16] = {0,};
int stack[100];
int top = -1;

int q[100];
int pre = 0, tail = 0;

void _dfs() {
int stIdx = 0;
int currIdx = 0;
// init push
stack[++top] = currIdx; // push

while(1) {
if(top==-1) 
break;

currIdx = stack[top--]; //pop
cout<<currIdx<<endl;
if(currIdx*2+2 <= 16)
stack[++top] = currIdx*2+2; // push child 1
else {
}

if(currIdx*2+1 <= 16) 
stack[++top] = currIdx*2+1; // push child 2
else {
}
}
}


void _bfs() {
int stIdx = 0;
int currIdx = 0;
// init push
q[tail++] = currIdx; // push

while(1) {
if(pre==tail) 
break;

currIdx = q[pre++]; //pop
cout<<currIdx<<endl;
if(currIdx*2+1 <= 16) {
q[tail++] = currIdx*2+1; // push child 1
}
else {
}

if(currIdx*2+2 <= 16) 
q[tail++] = currIdx*2+2; // push child 2
else {
}
}
}

int main() {
//init
for(int i=0;i<16;i++) {
arr[i] = i;
}

//_dfs();
_bfs();
return 0;
}