updated KnightsTourBoard.java
git-svn-id: svn://anubis/gvsu@81 45c1a28c-8058-47b2-ae61-ca45b979098e
This commit is contained in:
parent
51dc17a7d4
commit
5462edb8e8
@ -1,6 +1,4 @@
|
||||
|
||||
import java.util.Vector;
|
||||
|
||||
public class KnightsTourBoard
|
||||
{
|
||||
protected int m_width;
|
||||
@ -10,5 +8,47 @@ public class KnightsTourBoard
|
||||
KnightsTourBoard(int width, int height)
|
||||
{
|
||||
m_board = new int[width][height];
|
||||
for (int x = 0; x < m_width; x++)
|
||||
for (int y = 0; y < m_height; y++)
|
||||
m_board[x][y] = 0;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
m_board[startx][starty] = 1;
|
||||
return tourFrom(2, startx, starty);
|
||||
}
|
||||
|
||||
private boolean tourFrom(int nextStep, int startx, int 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) /* 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;
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user