We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
optimal C++ solution that passes all test cases and is O(1) whenever "Impossible" and otherwise O(max(|i_start-i_end|, |j_start-j_end|)), which is at most O(n). The idea is that all reachable positions form a hexagonal lattice, so we can check in O(1) time whether it's possible based on the parities of iend-istart and jend-jstart. If it is possible, then we can split into two general cases: case 1 is when abs(ie-is) <= 2 abs(je-js) for which case it's trivial; just move diagonally in one direction and horizontally to make up the distance (or those two in the opposite order, depending on the priorities). Case 2 is when abs(ie-is) > 2 abs(je-js), for which case it's slightly trickier, but always consists of moving diagonally in one direction then diagonally in another. In case 2 we need to watch out for going out of bounds and zigzag along the border to prevent that from happening, but otherwise it's not too difficult.
Red Knight's Shortest Path
You are viewing a single comment's thread. Return to all comments →
optimal C++ solution that passes all test cases and is O(1) whenever "Impossible" and otherwise O(max(|i_start-i_end|, |j_start-j_end|)), which is at most O(n). The idea is that all reachable positions form a hexagonal lattice, so we can check in O(1) time whether it's possible based on the parities of iend-istart and jend-jstart. If it is possible, then we can split into two general cases: case 1 is when abs(ie-is) <= 2 abs(je-js) for which case it's trivial; just move diagonally in one direction and horizontally to make up the distance (or those two in the opposite order, depending on the priorities). Case 2 is when abs(ie-is) > 2 abs(je-js), for which case it's slightly trickier, but always consists of moving diagonally in one direction then diagonally in another. In case 2 we need to watch out for going out of bounds and zigzag along the border to prevent that from happening, but otherwise it's not too difficult.