首页 > 解决方案 > 节点结构在扩展期间获得自己作为父节点

问题描述

我的任务是为 3x3 滑动瓷砖拼图编写一个求解器,该拼图必须稍后嵌入。

我有结构

struct node
{
 char state[9];
 struct node* parentNode;
 char lastMove;
} node;

我使用伪堆栈

struct node
{
 char state[9];
 struct node* parentNode;
 char lastMove;
} node;

我使用了一个堆栈,稍后将用于 IDS 算法。

struct node stack[60000];
struct node* Node = stack;
#define push(Node, n) (*((Node)++) = (n))
#define pop(Node) (*--(Node))

我的函数 expandNode 创建其给定父节点的所有有效子节点

void expandNode(struct node* parent)
{
char help;
int emptyField = -1;
struct node newNode;
for (int i = 0; i < 9; i++)
{
    if (parent->state[i] == '0') emptyField = i;
}

for (int i = 0; i < 4; i++)
{
    if(lastMoveVal(parent->lastMove, moves[i]) == '0') continue;
    if (moveValid(parent->state, moves[i]) == '1')
    {
        newNode.parentNode = parent;
     ...

我的主要功能

void main()
{
 struct node root;
 char rootState[9] = { '6','8','3','0','4','5','1','7','2' };
 assignArray(root.state, rootState);
 push(Node, root);
 struct node curr;
 curr  = pop(Node);
 expandNode(&curr);
 for(int i = 0; i < 10; i++)
 {
    curr = pop(Node);
    printf("\n");
    for(int j = 0; j<9; j++)
    {
        printf("%c", curr.state[j]);
    };
    printf("  PARENT: ");
    for(int j = 0; j<9; j++)
    {
        printf("%c", curr.parentNode->state[j]);
    };
  }
 }

这是输出:
683405172 父:683405172
683145072 父:683145072
083645172 父:083645172

如您所见,节点的扩展是正确的,但父节点的状态不是预期的 683045172 而是节点本身的状态。

标签: cpointers

解决方案


推荐阅读