Привет
Я пишу программу для решения 9 задач с помощью BFS, которая прилагается ниже.
Я хочу изменить этот код, чтобы он использовал dfs. в моих BFS я использовал массив и 2 указателя для имитации очереди и каждый раз помещал преемника в конец очереди
Я не знаю, что я должен сделать, чтобы изменить его на DFS.
что мне делать?
#include <stdio.h>
#include <conio.h>
#define MAX_QUEUE_SIZE 1000
struct State
{
int table[3][3];
};
struct Queue
{
State contents[MAX_QUEUE_SIZE];
int front;
int count;
};
//prototypes of functions
int checkGoal(State curState);
State* findChilds(State state);
void printState(State state);
int main()
{
//number of steps
int nodesNumber=0;
//initial state
State s0;
s0.table[0][0]=1;
s0.table[0][1]=2;
s0.table[0][2]=3;
s0.table[1][0]=4;
s0.table[1][1]=8;
s0.table[1][2]=5;
s0.table[2][0]=7;
s0.table[2][1]=9;
s0.table[2][2]=6;
Queue queue={NULL,0,0};
queue.contents[queue.count++]=s0;
//check that if the front node in queue pass the goal test finish the program
while(checkGoal(queue.contents[queue.front])!=1)
{
nodesNumber++;
//removeing front node from queue and shift front pointer to next one
State curState = queue.contents[queue.front++];
//print current state table
printState(curState);
//getting successors of current state
State* childStates=findChilds(curState);
//putting successors to queue
for(int i=0;i<4;i++)
queue.contents[queue.count++]=childStates[i];
}
printState(queue.contents[queue.front]);
printf("Number of Nodes Which Were Tested In BFS Tree is : %d\n",nodesNumber);
getch();
return 0;
}
//if even one of the cells of the table are not equal to its number correct will be false
int checkGoal(State curState)
{
int correct=1;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(curState.table[i][j]!=(i*3+j+1))
{
correct=0;
}
}
}
return correct;
}
void printState(State state)
{
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++)
printf("%d ",state.table[i][j]);
printf("\n");
}
printf("\n\n");
}
//return list of childs of given state
State* findChilds(State state)
{
State* newStates=new State[4];
//temporary table
int x[3][3];
int a,b,counter=0;
//creating all possible states
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
for(a=0;a<3;a++)
for(int b=0;b<3;b++)
x[a][b] = state.table[a][b];
//rotating
int temp = x[i][j+1];
x[i][j+1] = x[i][j];
x[i][j] = x[i+1][j];
x[i+1][j] = x[i+1][j+1];
x[i+1][j+1] = temp;
State newState;
for(a=0;a<3;a++)
for(b=0;b<3;b++)
newState.table[a][b]=x[a][b];
//putting new state in the queue
newStates[counter++]=newState;
}
}
return newStates;
}