| 27 | } |
| 28 | |
| 29 | public static boolean path(int board[][], int row, int col, int move, int posx[], int posy[]) |
| 30 | { |
| 31 | board[row][col] = move; |
| 32 | |
| 33 | // if all the positions are visited then print the result |
| 34 | if (move == board.length*board.length) |
| 35 | { |
| 36 | // printing result in matrix form |
| 37 | for (int i = 0; i < board.length; i++) |
| 38 | { |
| 39 | for (int j = 0; j < board.length; j++) |
| 40 | if (board[i][j] < 10) |
| 41 | System.out.print("0" + board[i][j] + " "); |
| 42 | else |
| 43 | System.out.print(board[i][j] + " "); |
| 44 | System.out.println(); |
| 45 | } |
| 46 | return true; |
| 47 | } |
| 48 | for (int i = 0; i < 8; i++) |
| 49 | { |
| 50 | int newx = row + posx[i]; |
| 51 | int newy = col + posy[i]; |
| 52 | |
| 53 | // checking if the new position is a valid move and not visited yet |
| 54 | if (validmove(newx, newy, board) && board[newx][newy] == 0) |
| 55 | { |
| 56 | if (path(board, newx, newy, move + 1, posx, posy)) |
| 57 | { |
| 58 | return true; |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // if position is not valid mark position as unvisited in the matrix |
| 64 | board[row][col] = 0; |
| 65 | return false; |
| 66 | } |
| 67 | |
| 68 | // checks that the new position is not outside the matrix of n*n |
| 69 | static boolean validmove(int newx, int newy, int board[][]) |