diff --git a/cs621/proj4/KnightsTourBoard.java b/cs621/proj4/KnightsTourBoard.java index c130280..5f6e18b 100644 --- a/cs621/proj4/KnightsTourBoard.java +++ b/cs621/proj4/KnightsTourBoard.java @@ -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; } }