对于网格中上下移动的问题,遇到很多次了,要合理的使用偏置矩阵来代替if条件语句
1 /** 2 使用if语句 3 */ 4 class Solution { 5 int X = 0; 6 int Y = 0; 7 Set<String> set; 8 public int robotSim(int[] commands, int[][] obstacles) { 9 int ans = 0; 10 set = new HashSet<>(); 11 for(int[] x : obstacles){ 12 set.add(x[0]+"|"+x[1]); 13 } 14 int count = 0; 15 for(int i = 0; i < commands.length; i++){ 16 if(commands[i] == -1) count = (count+1)%4; 17 else if(commands[i] == -2) count = (count+3)%4; 18 else{ 19 isObs(obstacles,X, Y, count,commands[i] ); 20 ans = Math.max(ans,X*X+Y*Y); 21 } 22 } 23 return ans; 24 } 25 26 27 public void isObs(int[][] obstacles,int x, int y, int count,int com ){ 28 if(count == 0){ 29 for(int i = 0; i < com; i++){ 30 Y++; 31 if(set.contains(X+"|"+Y)){ 32 Y--; 33 return ; 34 } 35 } 36 } 37 else if(count == 2){ 38 for(int i = 0; i < com; i++){ 39 Y--; 40 if(set.contains(X+"|"+Y)){ 41 Y++; 42 return ; 43 } 44 } 45 } 46 else if(count == 1){ 47 for(int i = 0; i < com; i++){ 48 X++; 49 if(set.contains(X+"|"+Y)){ 50 X--; 51 return ; 52 } 53 } 54 } 55 else if(count == 3){ 56 for(int i = 0; i < com; i++){ 57 X--; 58 if(set.contains(X+"|"+Y)){ 59 X++; 60 return ; 61 } 62 } 63 } 64 } 65 66 }
2.使用偏置矩阵
1 class Solution { 2 int X = 0; 3 int Y = 0; 4 Set<String> set; 5 public int robotSim(int[] commands, int[][] obstacles) { 6 int ans = 0; 7 set = new HashSet<>(); 8 for(int[] x : obstacles){ 9 set.add(x[0]+"|"+x[1]); 10 } 11 int[] dx = {0,1,0,-1}; 12 int[] dy = {1,0,-1,0}; 13 int count = 0; 14 for(int i = 0; i < commands.length; i++){ 15 if(commands[i] == -1) count = (count+1)%4; 16 else if(commands[i] == -2) count = (count+3)%4; 17 else{ 18 for(int j = 0; j < commands[i]; j++){ 19 X += dx[count]; 20 Y += dy[count]; 21 if(set.contains(X+"|"+Y)){ 22 X -= dx[count]; 23 Y -= dy[count]; 24 break; 25 } 26 } 27 ans = Math.max(ans,X*X+Y*Y); 28 } 29 } 30 // System.out.println(X+"|"+Y); 31 return ans; 32 } 33 }
原文:https://www.cnblogs.com/leechee9/p/12095662.html