Use this to learn the idea, then write your own version.
1class Solution {2 public boolean canMouseWin(String[] grid, int catJump, int mouseJump) {3 final int m = grid.length;4 final int n = grid[0].length();5 int nFloors = 0;6 int cat = 0; 7 int mouse = 0; 8 9 for (int i = 0; i < m; ++i)10 for (int j = 0; j < n; ++j) {11 if (grid[i].charAt(j) != '#')12 ++nFloors;13 if (grid[i].charAt(j) == 'C')14 cat = hash(i, j, n);15 else if (grid[i].charAt(j) == 'M')16 mouse = hash(i, j, n);17 }18 19 Boolean[][][] mem = new Boolean[m * n][m * n][nFloors * 2];20 return canMouseWin(grid, cat, mouse, 0, catJump, mouseJump, m, n, nFloors, mem);21 }22 23 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};24 25 26 27 private boolean canMouseWin(String[] grid, int cat, int mouse, int turn, int catJump,28 int mouseJump, int m, int n, int nFloors, Boolean[][][] mem) {29 30 if (turn == nFloors * 2)31 return false;32 if (mem[cat][mouse][turn] != null)33 return mem[cat][mouse][turn];34 35 if (turn % 2 == 0) {36 37 int i = mouse / n;38 int j = mouse % n;39 for (int[] dir : DIRS) {40 for (int jump = 0; jump <= mouseJump; ++jump) {41 int x = i + dir[0] * jump;42 int y = j + dir[1] * jump;43 if (x < 0 || x == m || y < 0 || y == n)44 break;45 if (grid[x].charAt(y) == '#')46 break;47 48 if (grid[x].charAt(y) == 'F')49 return mem[cat][mouse][turn] = true;50 if (canMouseWin(grid, cat, hash(x, y, n), turn + 1, catJump, mouseJump, m, n, nFloors,51 mem))52 return mem[cat][mouse][turn] = true;53 }54 }55 56 return mem[cat][mouse][turn] = false;57 } else {58 59 final int i = cat / n;60 final int j = cat % n;61 for (int[] dir : DIRS)62 for (int jump = 0; jump <= catJump; ++jump) {63 final int x = i + dir[0] * jump;64 final int y = j + dir[1] * jump;65 if (x < 0 || x == m || y < 0 || y == n)66 break;67 if (grid[x].charAt(y) == '#')68 break;69 70 if (grid[x].charAt(y) == 'F')71 return mem[cat][mouse][turn] = false;72 final int nextCat = hash(x, y, n);73 if (nextCat == mouse)74 return mem[cat][mouse][turn] = false;75 if (!canMouseWin(grid, nextCat, mouse, turn + 1, catJump, mouseJump, m, n, nFloors, mem))76 return mem[cat][mouse][turn] = false;77 }78 79 return mem[cat][mouse][turn] = true;80 }81 }82 83 private int hash(int i, int j, int n) {84 return i * n + j;85 }86}87