# Java. fix the code. explain to me why my code isn't correct

Anonymous

Question description

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);

}

}

Studypool has helped 1,244,100 students
flag Report DMCA

Brown University

1271 Tutors

California Institute of Technology

2131 Tutors

Carnegie Mellon University

982 Tutors

Columbia University

1256 Tutors

Dartmouth University

2113 Tutors

Emory University

2279 Tutors

Harvard University

599 Tutors

Massachusetts Institute of Technology

2319 Tutors

New York University

1645 Tutors

Notre Dam University

1911 Tutors

Oklahoma University

2122 Tutors

Pennsylvania State University

932 Tutors

Princeton University

1211 Tutors

Stanford University

983 Tutors

University of California

1282 Tutors

Oxford University

123 Tutors

Yale University

2325 Tutors