gvsu/cs621/proj4/KnightsTourBoard.java
josh bc575f8430 tour board working
git-svn-id: svn://anubis/gvsu@83 45c1a28c-8058-47b2-ae61-ca45b979098e
2008-03-27 23:04:01 +00:00

59 lines
1.9 KiB
Java

public class KnightsTourBoard
{
protected int m_width;
protected int m_height;
protected int[][] m_board;
KnightsTourBoard(int width, int height)
{
m_width = width;
m_height = height;
m_board = new int[width][height];
}
public int getWidth() { return m_width; }
public int getHeight() { return m_height; }
public int getStepAt(int x, int y) { return m_board[x][y]; }
public boolean tour(int startx, int starty)
{
for (int x = 0; x < m_width; x++)
for (int y = 0; y < m_height; y++)
m_board[x][y] = 0;
m_board[startx][starty] = 1;
return tourFrom(2, startx, starty);
}
private boolean tourFrom(int nextStep, int startx, int starty)
{
// System.out.println("tourFrom(" + nextStep + ", " +
// startx + ", " + starty + ")");
final int[] xoffsets = {-2, -1, 1, 2, -2, -1, 1, 2};
final int[] yoffsets = {-1, -2, -2, -1, 1, 2, 2, 1};
for (int moveIndex = 0; moveIndex < 8; moveIndex++)
{
int x = startx + xoffsets[moveIndex];
int y = starty + yoffsets[moveIndex];
if (x >= 0 && x < m_width && y >= 0 && y < m_height)
{
if (m_board[x][y] == 0) /* if space has not been visited yet */
{
m_board[x][y] = nextStep; /* we just took step number
* nextStop, stop if that is all
* we needed to do */
if (nextStep == m_width * m_height)
return true;
if (tourFrom(nextStep + 1, x, y)) /* else walk from there */
return true;
m_board[x][y] = 0; /* this step did not lead to a solution */
}
}
}
return false;
}
}