Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.LinkedList;
- import java.util.Scanner;
- public class ccc10j5 {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int startR = sc.nextInt()-1;
- int startC = sc.nextInt()-1;
- int endR = sc.nextInt()-1;
- int endC = sc.nextInt()-1;
- int[][] step = new int[8][8];
- //fill with Integer.MAX_VALUE
- for (int r=0; r<8; r++) {
- Arrays.fill(step[r], Integer.MAX_VALUE);
- }
- LinkedList<Integer> rQ = new LinkedList<Integer>();
- LinkedList<Integer> cQ = new LinkedList<Integer>();
- //initialize beginning location
- step[startR][startC] = 0;
- rQ.add(startR);
- cQ.add(startC);
- while(!rQ.isEmpty()) {
- int r = rQ.poll(); //read current position's row
- int c = cQ.poll();
- //1. r-2 c+1
- if (r-2>=0 && c+1<8 //check the boudary
- && step[r-2][c+1]>step[r][c]+1) {
- step[r-2][c+1] = step[r][c]+1;
- rQ.add(r-2);
- cQ.add(c+1);
- }
- //2. r-1 c+2
- if (r-1>=0 && c+2<8 //check the boudary
- && step[r-1][c+2]>step[r][c]+1) {
- step[r-1][c+2] = step[r][c]+1;
- rQ.add(r-1);
- cQ.add(c+2);
- }
- //3. r+1 c+2
- //4. r+2 c+1
- //5. r+2 c-1
- //6. r+1 c-2
- //7 r-1 c-2
- //8 r-2 c-1
- }
- System.out.println(step[endR][endC]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement