Need this asap
I wrote the code for the Knight’s tour. fix the code so that it finds a correct solution, do not start from scratch. Explain why my code isn’t correct. Why does it appear to have 15 four times in the solution? I know the number is only suppose to be there once. My code does not give the correct solution, because what I just explain before, why is this?
public class Knight
{
int[][] m_board;
int m_count = 0;
Knight(int nrRows, int nrCols)
{
m_board = new int[nrRows][nrCols];
for(int i = 0; i < nrRows; ++i)
for(int j = 0; j < nrCols; ++j)
m_board[i][j] = 0;
}
public int GetNrRows() { return m_board.length;}
public int GetNrCols() { return m_board[0].length;}
public void Solve(int r, int c)
{
m_board[r][c] = 1;
Tour(r,c);
Print();
}
public boolean Tour(int r, int c)
{
if(m_board[r][c] == GetNrRows() * GetNrCols())
return true;
int[] mr = {-1,-2,-2,-1,+1,+2,+2,+1};
int[] mc = {-2,-1,+1,+2,+2,+1,-1,-2};
for(int k = 0; k < mr.length; ++k)
{
int newr = r + mr[k];
int newc = c + mc[k];
if(IsValid(newr, newc))
{
m_board[newr][newc] = m_board[r][c] + 1;
Tour(newr, newc);
}
}
return false;
}
public boolean IsValid(int newr, int newc)
{
return
newr >= 0 && newr < GetNrRows() &&
newc >= 0 && newc < GetNrCols() &&
m_board[newr][newc] == 0;
}
public void Print()
{
for(int r = 0; r < m_board.length; ++r)
{
for(int c = 0; c < m_board[0].length; ++c)
System.out.format(“%4d”, m_board[r][c]);
System.out.println();
}
System.out.println(” …. count = ” + m_count);
}
}


0 comments