骑士之旅 C++

发布于 2024-12-08 15:45:05 字数 3244 浏览 0 评论 0原文

我正在尝试使用递归回溯来解决骑士之旅问题。有人可以帮我优化我的代码吗?我的代码可以工作到 6X6 板。 。当 N=7 后,求解 需要几乎无限的时间。 这是我的代码:

#include <iostream>
#include "genlib.h"
#include "grid.h"
#include "vector.h"
#include <iomanip>

const int NOT_VISITED = -1;
//Size of the board
const int N = 6;
const int N2 = N*N;

typedef Grid<int> chess;

struct position{
    int row;
    int col;
};

//Initializes the board and makes each and every
//square value as NOT_VISITED
void initializeBoard(chess &board)
{
    for(int i=0;i<board.numRows();i++)
        for(int j=0;j<board.numCols();j++)
            board[i][j] = NOT_VISITED;
}

//Returns true if the square is visited;
bool visited(chess &board,position square)
{
    return board[square.row][square.col ] != NOT_VISITED;
}

//Returns true if the givien position variable is outside the chess board
bool outsideChess(chess &board, position square)
{
    if(square.row <board.numRows() && square.col <board.numCols() && square.row >=0 && square.col >=0)
        return false;
    return true;
}

void visitSquare(chess &board,position square,int count)
{
    board[square.row] [square.col] = count;
}

void unVisitSquare(chess &board,position square)
{
    board[square.row] [square.col] = NOT_VISITED;
}

position next(position square,int irow, int icol)
{
    square.row += irow;
    square.col += icol;
    return square;
}
Vector<position> calulateNextSquare(chess board,position square)
{
    Vector<position> list;
    for(int i=-2;i<3;i=i+4)
    {
        for(int j=-1;j<2;j=j+2)
        {
            list.add(next(square,i,j));
            list.add(next(square,j,i));
        }
    }
    return list;

}

bool knightTour(chess &board,position square, int count)
{
    //cout<<count<<endl;
    //Base Case if the problem is solved;
    if(count>N2)
        return true;
    if(outsideChess(board,square))
        return false;
    //return false if the square is already visited
    if(visited(board,square))
        return false;
    visitSquare(board,square,count);
    Vector<position> nextSquareList = calulateNextSquare(board,square); 
    for(int i=0;i<nextSquareList.size();i++)
        if(knightTour(board, nextSquareList[i], count+1))
            return true;
    unVisitSquare(board,square);
    return false;
}


void printChess(chess &board)
{
    for(int i=0;i<board.numRows();i++)
    {
        for(int j=0;j<board.numCols();j++)
            cout<<setw(4)<<board[i][j];
        cout<<endl;
    }
}


int main()
{
    chess board(N,N);
    initializeBoard(board);
    position start;
    start.row = 0; start.col = 0;
    if(knightTour(board,start,1))
        printChess(board);
    else
        cout<<"Not Possible";
    return 0;
}

我正在使用斯坦福 106B 图书馆(网格是二维向量) Visual studio 2008 包含所需库文件的空白项目 https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0BwLe9NJT8IreNWU0N2M5MGUtY2UxZC00ZTY2LWE1YjQtMjgxYzAxMWE3OWU2&hl=en

I am trying to solve Knight Tour Problem using recursive Backtracking. Can someone help me optimize my code. My code works till 6X6 board. . After N=7 it takes almost infinite time to solve .
Here is my code :

#include <iostream>
#include "genlib.h"
#include "grid.h"
#include "vector.h"
#include <iomanip>

const int NOT_VISITED = -1;
//Size of the board
const int N = 6;
const int N2 = N*N;

typedef Grid<int> chess;

struct position{
    int row;
    int col;
};

//Initializes the board and makes each and every
//square value as NOT_VISITED
void initializeBoard(chess &board)
{
    for(int i=0;i<board.numRows();i++)
        for(int j=0;j<board.numCols();j++)
            board[i][j] = NOT_VISITED;
}

//Returns true if the square is visited;
bool visited(chess &board,position square)
{
    return board[square.row][square.col ] != NOT_VISITED;
}

//Returns true if the givien position variable is outside the chess board
bool outsideChess(chess &board, position square)
{
    if(square.row <board.numRows() && square.col <board.numCols() && square.row >=0 && square.col >=0)
        return false;
    return true;
}

void visitSquare(chess &board,position square,int count)
{
    board[square.row] [square.col] = count;
}

void unVisitSquare(chess &board,position square)
{
    board[square.row] [square.col] = NOT_VISITED;
}

position next(position square,int irow, int icol)
{
    square.row += irow;
    square.col += icol;
    return square;
}
Vector<position> calulateNextSquare(chess board,position square)
{
    Vector<position> list;
    for(int i=-2;i<3;i=i+4)
    {
        for(int j=-1;j<2;j=j+2)
        {
            list.add(next(square,i,j));
            list.add(next(square,j,i));
        }
    }
    return list;

}

bool knightTour(chess &board,position square, int count)
{
    //cout<<count<<endl;
    //Base Case if the problem is solved;
    if(count>N2)
        return true;
    if(outsideChess(board,square))
        return false;
    //return false if the square is already visited
    if(visited(board,square))
        return false;
    visitSquare(board,square,count);
    Vector<position> nextSquareList = calulateNextSquare(board,square); 
    for(int i=0;i<nextSquareList.size();i++)
        if(knightTour(board, nextSquareList[i], count+1))
            return true;
    unVisitSquare(board,square);
    return false;
}


void printChess(chess &board)
{
    for(int i=0;i<board.numRows();i++)
    {
        for(int j=0;j<board.numCols();j++)
            cout<<setw(4)<<board[i][j];
        cout<<endl;
    }
}


int main()
{
    chess board(N,N);
    initializeBoard(board);
    position start;
    start.row = 0; start.col = 0;
    if(knightTour(board,start,1))
        printChess(board);
    else
        cout<<"Not Possible";
    return 0;
}

i am using Stanford 106B Libraries( grid is a 2 dimensional vector )
Visual studio 2008 Blank project with required library files https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0BwLe9NJT8IreNWU0N2M5MGUtY2UxZC00ZTY2LWE1YjQtMjgxYzAxMWE3OWU2&hl=en

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撑一把青伞 2024-12-15 15:45:05

我想说,首先,摆脱这个:

Vector<position> nextSquareList = calulateNextSquare(board,square);

在每个步骤上创建一个向量将花费大量时间。您可以使用数组(固定大小,因为您知道有 8 种可能的移动),或者完全展开循环 。与与您的版本类似的版本进行比较。

I'd say, for a start, get rid of this:

Vector<position> nextSquareList = calulateNextSquare(board,square);

creating a Vector on each step will take a lot of time. You could either use an array (fixed sized, since you know there are 8 possible moves), or unroll the loop entirely. Compare with this version, similar to yours.

我也只是我 2024-12-15 15:45:05

我想建议一些修改:

#include <iostream>
#include "genlib.h"
#include "grid.h"
#include "vector.h"
#include <iomanip>

const int NOT_VISITED = -1;
//Size of the board
const int N = 6;
const int N2 = N*N;

typedef int chess[N][N]; // <------------- HERE

struct position{
    int row;
    int col;
};

//Initializes the board and makes each and every
//square value as NOT_VISITED
void initializeBoard(chess &board)
{
    for(int i=0;i<board.numRows();i++)
        for(int j=0;j<board.numCols();j++)
            board[i][j] = NOT_VISITED;
}

//Returns true if the square is visited;
bool visited(chess &board,position square)
{
    return board[square.row][square.col ] != NOT_VISITED;
}

//Returns true if the givien position variable is outside the chess board
bool outsideChess(chess &board, position square)
{
    if(square.row <board.numRows() && square.col <board.numCols() && square.row >=0 && square.col >=0)
        return false;
    return true;
}

void visitSquare(chess &board,position square,int count)
{
    board[square.row] [square.col] = count;
}

void unVisitSquare(chess &board,position square)
{
    board[square.row] [square.col] = NOT_VISITED;
}

position next(position square,int irow, int icol)
{
    square.row += irow;
    square.col += icol;
    return square;
}
void calulateNextSquare(chess board,position square, Vector<position>& list)  // <------------- HERE
{
    // ------------- HERE
    //Also, change this part to add only unvisited and not out-of-board positions.
    for(int i=-2;i<3;i=i+4)
    {
        for(int j=-1;j<2;j=j+2)
        {
            list.add(next(square,i,j));
            list.add(next(square,j,i));
        }
    }
}

bool knightTour(chess &board,position square, int count)
{
    //cout<<count<<endl;
    //Base Case if the problem is solved;
    if(count>N2)
        return true;
    if(outsideChess(board,square))
        return false;
    //return false if the square is already visited
    if(visited(board,square))
        return false;
    visitSquare(board,square,count);
    Vector<position> nextSquareList;  // <------------- HERE
    calulateNextSquare(board,square,nextSquareList); 
    for(int i=0;i<nextSquareList.size();i++)
        if(knightTour(board, nextSquareList[i], count+1))
            return true;
    unVisitSquare(board,square);
    return false;
}


void printChess(chess &board)
{
    for(int i=0;i<board.numRows();i++)
    {
        for(int j=0;j<board.numCols();j++)
            cout<<setw(4)<<board[i][j];
        cout<<endl;
    }
}


int main()
{
    chess board(N,N);
    initializeBoard(board);
    position start;
    start.row = 0; start.col = 0;
    if(knightTour(board,start,1))
        printChess(board);
    else
        cout<<"Not Possible";
    return 0;
}

但请注意,您仍然具有指数复杂性,并且优化你的代码不会改变它。

Some modifications I would like to suggest:

#include <iostream>
#include "genlib.h"
#include "grid.h"
#include "vector.h"
#include <iomanip>

const int NOT_VISITED = -1;
//Size of the board
const int N = 6;
const int N2 = N*N;

typedef int chess[N][N]; // <------------- HERE

struct position{
    int row;
    int col;
};

//Initializes the board and makes each and every
//square value as NOT_VISITED
void initializeBoard(chess &board)
{
    for(int i=0;i<board.numRows();i++)
        for(int j=0;j<board.numCols();j++)
            board[i][j] = NOT_VISITED;
}

//Returns true if the square is visited;
bool visited(chess &board,position square)
{
    return board[square.row][square.col ] != NOT_VISITED;
}

//Returns true if the givien position variable is outside the chess board
bool outsideChess(chess &board, position square)
{
    if(square.row <board.numRows() && square.col <board.numCols() && square.row >=0 && square.col >=0)
        return false;
    return true;
}

void visitSquare(chess &board,position square,int count)
{
    board[square.row] [square.col] = count;
}

void unVisitSquare(chess &board,position square)
{
    board[square.row] [square.col] = NOT_VISITED;
}

position next(position square,int irow, int icol)
{
    square.row += irow;
    square.col += icol;
    return square;
}
void calulateNextSquare(chess board,position square, Vector<position>& list)  // <------------- HERE
{
    // ------------- HERE
    //Also, change this part to add only unvisited and not out-of-board positions.
    for(int i=-2;i<3;i=i+4)
    {
        for(int j=-1;j<2;j=j+2)
        {
            list.add(next(square,i,j));
            list.add(next(square,j,i));
        }
    }
}

bool knightTour(chess &board,position square, int count)
{
    //cout<<count<<endl;
    //Base Case if the problem is solved;
    if(count>N2)
        return true;
    if(outsideChess(board,square))
        return false;
    //return false if the square is already visited
    if(visited(board,square))
        return false;
    visitSquare(board,square,count);
    Vector<position> nextSquareList;  // <------------- HERE
    calulateNextSquare(board,square,nextSquareList); 
    for(int i=0;i<nextSquareList.size();i++)
        if(knightTour(board, nextSquareList[i], count+1))
            return true;
    unVisitSquare(board,square);
    return false;
}


void printChess(chess &board)
{
    for(int i=0;i<board.numRows();i++)
    {
        for(int j=0;j<board.numCols();j++)
            cout<<setw(4)<<board[i][j];
        cout<<endl;
    }
}


int main()
{
    chess board(N,N);
    initializeBoard(board);
    position start;
    start.row = 0; start.col = 0;
    if(knightTour(board,start,1))
        printChess(board);
    else
        cout<<"Not Possible";
    return 0;
}

But please note that you still have a exponential complexity, and optimizing your code wont change it.

人生百味 2024-12-15 15:45:05

您正在将棋盘的副本传递给calculateNextSquare,但似乎在此方法中不需要它。

此外,您在此方法中返回一个向量,但您应该通过引用传递它。

You are passing a copy of the board to calculateNextSquare but it seems you don't need it in this method.

Also, you return a vector in this method but you should pass it by reference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文