【问题标题】:Knights tour passing arrays to linked list and more骑士游览将数组传递到链表等
【发布时间】:2014-03-24 13:09:59
【问题描述】:

我目前正在从事骑士巡回赛项目。我的最终目标是使用回溯(通过实现堆栈)和 Warnsdorff 的启发式方法来创建这个项目。我不允许使用任何已经创建了堆栈函数的库,例如 push 和 pop。我也不允许使用递归来解决问题。话虽如此,我现在很困,我的下一个重要里程碑将是仅通过回溯来解决问题。

我根本不会粉饰这个,但现在我的代码是一团糟。我几乎已经创建了使程序运行所需的所有工具,但现在我只需要将所有部分放在一起即可。

以下是我的代码:

#include<iostream>
using namespace std;

class linkedList{

struct node
{
    int data;
    node *next;
};

node *top;

public:
linkedList()
{
    top = NULL;
}
void push(int coordinates)
{
    node *p = new node;
    p -> data = coordinates;
    p -> next = top;
    top = p;
}
int pop()
{
    node *temp = top;
    top = temp -> next;
    return temp -> data;
}
int display()
{
        cout<<"\n"<< top -> data;
        top = top-> next;

}

};


// Linked List ================================================

class Board{
public:
int next;
int status[8][8];
Board();
void print();
};

Board::Board(){

  for(int i=0; i<8; i++){
    for(int j=0; j<8; j++){
      status[i][j] = -1;
    }
  }

}//constructor


void Board::print(){

  for (int j=0; j<8; j++){
    for(int i=0; i<8;i++){
      cout << status[i][j] << "   ";
    }
    cout << endl << endl;
  }

}
//BOARD========================================================

class Knight {

 private:
 public:
int vertical[8] = {2,-2,1,-1,2,-2,1,-1}; // possible knight moves x coordinate
int horizontal[8] = {1,1,2,2,-1,-1,-2,-2}; // possible knight move y coordinate
int counter;
int currentPos[2];
Knight();
};

Knight::Knight(){
currentPos[0] = 7; // x-coordiante
currentPos[1] = 7; // y-coordinate
counter = 0;

}//constructor

/* Use this later

int Knight::changePos(int i,int j){

Knight::currentPos[0] = (Knight::currentPos[0] + i);
Knight::currentPos[1] = (Knight::currentPos[1] + j);
counter++;
return counter;
*/

int main(){
    Board b;
    Knight k;

    b.status[k.currentPos[0]][k.currentPos[1]] = k.counter;
    b.print();

    linkedList obj;
    int coordinates;

}

所以我现在的想法是做到以下几点:

创建一个循环,使用水平和垂直数组(马可能的移动)改变马的当前位置。一旦位置发生变化,计数器将递增,并且 -1 将替换为当前计数器值。当骑士被移动后,需要使用我创建的推送函数将新坐标的信息传递给链表。为了做到这一点,我需要找出一种方法来传递一个数组 (x,y) 或多个值来推送。我还需要创建一些我目前正在处理的边界检查(确保骑士不会移动到他去过的地方并且不会离开棋盘)。最后,如果骑士确实卡住了,我需要使用我创建的弹出函数返回一步并尝试继续进行不同的移动。

我真的非常感谢您提供的任何帮助、更正、起点或其他建议!我被困住了..

【问题讨论】:

  • 我可以指出您不需要动态增长的链表吗?堆栈的最大大小为N*N(棋盘上的方格总数)。因此,您可以使用单个数组以及当前“堆叠”到其中的移动次数。
  • @BenVoigt 是选择使用 2D 坐标还是展平坐标平面都无关紧要。他需要一种方法来存储每次移动的坐标(可能还有更多信息),这样他就可以有效地回溯。

标签: c++ arrays linked-list stack knights-tour


【解决方案1】:

让我直说。您在实现允许您撤消移动的 Stack 结构时遇到了困难。

C++ 并不是我真正的强项,但这是我处理堆栈的方式

  1. 定义一个存储坐标(可能还有回溯信息)的结构
  2. 更新“节点”以存储指向新结构实例的指针。
  3. 更新“push()”定义以使用它。
  4. 更新“pop()”定义以返回它。
  5. 利润...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多