Indeed Coding Round 3 - Minimum Knight Move
unknown
plain_text
3 years ago
2.5 kB
0
Indexable
// | | | | | | | | | // -+---+---+---+---+---+---+---+---+- // | | | | | | G | | | // -+---+---+---+---+---+---+---+---+- // | | | | | | | | | // -+---+---+---+---+---+---+---+---+- // | | | O | | O | | | | // -+---+---+---+---+---+---+---+---+- // | | O | | | | O | | | // -+---+---+---+---+---+---+---+---+- // | | | | N | | | | | // -+---+---+---+---+---+---+---+---+- // | | O | | | | O | | | // -+---+---+---+---+---+---+---+---+- // | | | O | | O | | | | // -+---+---+---+---+---+---+---+---+- // | | | | | | | | | // -+---+---+---+---+---+---+---+---+- // | | | | | | | | | // start = [0, 0] // end = [10,10] class Main { List<List<Integer>> possibleMoves = Arrays.asList( {-1, -2}, {-1, -2}, {-1, -2}, {-1, -2}, {-1, -2}, {-1, -2}, {-1, -2}, {-1, -2} ); class MovePosition { List<Integer> pos; Integer numMove; // TODO } public int minKnight(int[] start, int[] end, HashMap<List<Integer>> obstacles) { HashSet<List<Integer>> visited = new HashSet<>(); Queue<MovePosition> q = new Queue<>(); MovePosition mp = new MovePosition(Arrays.asList(start), 0); List<List<Integer>> steps = new ArrayList<>(); while(!q.isEmpty()) { MovePosition move = q.poll(); List<Integer> currPos = move.pos; Integer currMove = move.numMove; for (List<Integer> move:possibleMoves) { int newX = currPos + move.get(0); int newY = currPos + move.get(1); List<Integer> newPos = Arrays.asList(newX, newY); if (!visited.contains(newPos) && !obstacles.contain(newPos)) { if (newX != end[0] && newY != end[1]) { List<Integer> pos = newPos; Integer numMove = currMove + 1; q.add(new MovePosition(pos, numMove)); visited.add(newPos); } else { // reach end return currMove + 1; } } } } return -1; } // O(8^M) // O(8^M) }
Editor is loading...