2

I have been reading up on C++ lately, especially STL, and I decided to do the Knights Tour problem again. I'm thinking about the best way to implement this, and I'm looking for some help.

Just for fun and practice, I thought I'd start with a "Piece" base class, which a "Knight" class can inherit from. I want to do this so I later can try adding other pieces(even though most of the pieces can't walk over the whole board and complete the problem).

So the "piece class" will need some sort of container to store the coordinates of the piece on the board and the number of moves it has made in that specific step.

I'm thinking I need a linked list with 64 (8 * 8) places to do this most efficiently, containing x,y and moves.

Looking at the STL containers, I can't find anything except map that will hold more than one type.

What can I do to store the coordinate pair and an int for the number of moves in one container? Are there more efficient ways of doing this than using vector, list or map? Do I need a custom container?

Thanks!

false
  • 10,264
  • 13
  • 101
  • 209
Q-bertsuit
  • 3,223
  • 6
  • 30
  • 55

3 Answers3

2

You can use

struct CellInfo
{
    int x, y, move_count;
}

And store it in std::vector for constant access.

Denis Ermolin
  • 5,530
  • 6
  • 27
  • 44
0

Apart from STL and encapsulation, a very efficient way is to use arrays:

pair<int, int> piece_pos[N];
int piece_move[N];

This avoids the overhead of memory leakage and is faster than dynamic allocation.

If you stell want to use STL, then:

vector<pair<int, int> > piece_pos(N);
vector<int> piece(N);
0

The C++ STL now has static arrays as well. If you want to store the number of times a given x,y coordinate has been moved to, you can create an array of arrays like the following:

using container_type = std::array<std::array<int, 8>, 8>;

// ...

container_type c;
int moves = c[x][y]; // constant-time access.

If you don't need to look moves up based on x,y, and just want the data stored efficiently, use a flat array of size 8x8 = 64.

If your compiler is out of date, consider using std::vector instead.

bstamour
  • 7,746
  • 1
  • 26
  • 39