您好 我编写了一个程序,用于解决由bfs解决的9问题。 我想更改此代码以使其使用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;
}
答案 0 :(得分:3)
BFS使用队列,DFS使用堆栈。在您的情况下,您需要做的就是选择数组后面的元素而不是前面的元素来将BFS变成DFS,即转向
State curState = queue.contents[queue.front++];
到
State curState = queue.contents[--queue.count];
并相应地更改引用queue.front
的其他部分。
答案 1 :(得分:1)
我不会尝试破译您的代码段,但请查看例如http://www.ics.uci.edu/~eppstein/161/960215.html(“BFS和DFS之间的关系”),用于最直接的转换。
如果您可以使您的代码看起来有点像该页面上的BFS示例,那么转换应该相对容易。