Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.hellojni;
- import java.util.ArrayList;
- import java.util.List;
- public class JavaSolver {
- private final static int base = 12;
- private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2},
- {-2, 1}, {-2, -1}, {-1, -2}};
- private static int[][] board;
- private static int total;
- private static int[][] formatGrid() {
- int[][] newGrid = new int[8][8];
- for(int i = 0; i < 8; i++) {
- for(int j = 0; j < 8; j++) {
- newGrid[i][j] = board[i+2][j+2];
- }
- }
- return newGrid;
- }
- public static int[][] createJavaSolution(int startRow, int startCol) {
- // Create board and populate it, boardsize is set to 2 wider than the actual board to
- // not have to do collision detection
- board = new int[base][base];
- total = (base - 4) * (base - 4);
- for (int r = 0; r < base; r++)
- for (int c = 0; c < base; c++)
- if (r < 2 || r > base - 3 || c < 2 || c > base - 3)
- board[r][c] = -1;
- int row = 2 + startRow;
- int col = 2 + startCol;
- board[row][col] = 1;
- solve(row, col, 2);
- return formatGrid();
- }
- private static boolean solve(int row, int col, int turn) {
- if (turn > total)
- return true;
- int[][] numbers = neighborsArray(row,col);
- int[] bestMove = new int[] {0,0,9};
- for (int i = 0; i < 8; i++) {
- if (numbers[i][2] < bestMove[2]) {
- bestMove[0] = numbers[i][0];
- bestMove[1] = numbers[i][1];
- }
- }
- row = bestMove[0];
- col = bestMove[1];
- board[row][col] = turn;
- if (solve(row, col, turn + 1))
- return true;
- board[row][col] = 0;
- return false;
- }
- private static List<int[]> neighbors(int row, int col) {
- List<int[]> numbers = new ArrayList<>();
- for (int i = 0; i < 8; i++) {
- int x = moves[i][0];
- int y = moves[i][1];
- if (board[row + y][col + x] == 0) {
- int num = countNeighbors(row + y, col + x);
- numbers.add(new int[]{row + y, col + x, num});
- }
- }
- return numbers;
- }
- private static int[][] neighborsArray(int row, int col) {
- int[][] numbers = new int[8][3];
- for (int i = 0; i < 8; i++) {
- int x = moves[i][0];
- int y = moves[i][1];
- if (board[row + y][col + x] == 0) {
- int num = countNeighbors(row + y, col + x);
- numbers[i][0] = row;
- numbers[i][1] = col;
- numbers[i][2] = num;
- }
- else {
- numbers[i][0] = row;
- numbers[i][1] = col;
- numbers[i][2] = 9;
- }
- }
- return numbers;
- }
- private static int countNeighbors(int row, int col) {
- int num = 0;
- for (int i = 0; i < 8; i++)
- if (board[row + moves[i][1]][col + moves[i][0]] == 0)
- num++;
- return num;
- }
- }
- // http://pastebin.com/LSqEHPu0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement