If anyone can take a second to view my code, I would really appreciate it. I've been working on this for days. I think I am so so close.

Its the Knights Tour (Knight must move to every spot on board without moving to one spot twice). It breaks when the knight has no good options, and has to backtrack. I'm guessing something is wrong with my return statements?

Any help would be great.

#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;

const int rowMoves [8] = {-2,-2, 1, 1, 2, 2, 1,-1};
const int colMoves [8] = {-1, 1,-2, 2, 1,-1,-2,-2};

int grid [8][8];
vector <int> pathRow;
vector <int> pathCol;
int counter = 0;
//int moveOption = 0;

bool ktour (int,int);

int main (void) 
{	
	int row = 0;
	int col = 0;

	ktour (row, col);
	system ("pause");
	return 1;
}

bool ktour (int row, int col)
{

	pathRow.push_back (row);
	pathCol.push_back (col);
	grid [row] [col] = 1;
	counter++;
	cout << pathRow.back() << ", " << pathCol.back();
	cout << "move #" << counter << endl;

	if (pathRow.size() == 64)
		return true;

	int possRow, possCol;

	for (int moveOption = 0; moveOption < 8; moveOption++)
	{
		possRow = row + rowMoves [moveOption];
		possCol = col + colMoves [moveOption];
		
		if (possRow < 8 && possRow >= 0 && possCol < 8 && possCol >= 0 && grid [possRow] [possCol] != 1)
		{
			if (ktour (possRow, possCol))
				return true;
		}
	}

	cout << "Popping back" << endl;
	pathRow.pop_back ();
	pathCol.pop_back ();
	counter--;
	
	return false;
}

Recommended Answers

All 2 Replies

http://www.daniweb.com/forums/thread273756.html
Switching languages won't aid your understanding of the recursive nature of the problem.

As I have researched recursion, I have learned that c++ is better for it, so I switched (Am I wrong?). Apparently that bothers you? You took the time to post, so I suppose it does.

People are always very friendly and helpful here.

So anyways, thanks for your insight.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.