import java.util.LinkedList; import java.util.Queue; class Solution { public boolean hasValidPath(int[][] grid) { int[][] visited = new int[grid.length][grid[0].length]; //创建新的数组,用于存放该位置是否已经被访问过 Queue<int[]> queue = new LinkedList<>(); //创建链表,用于存放路径 //方向 上下左右 int[][] vectors = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; queue.offer(new int[]{0, 0}); //插入原点坐标 visited[0][0] = 1;//对[0][0]位置进行标记 Queue<int[]> queue1 = new LinkedList<>(); while (!queue.isEmpty() || !queue1.isEmpty()) { if(!queue.isEmpty()) { int[] poll = queue.poll(); //返回队头 if (poll[0] == grid.length - 1 && poll[1] == grid[0].length - 1) return true; int way = 1; for (int[] vector : vectors) { int a = poll[0] + vector[0]; int b = poll[1] + vector[1]; if (a >= 0 && a < grid.length && b >= 0 && b < grid[0].length && visited[a][b] == 0) { int before = grid[poll[0]][poll[1]]; int after = grid[a][b]; if (isOk(before, after, way)) { if(way!=4){ queue1.add(poll); } queue.offer(new int[]{a, b}); visited[a][b] = 1; break; } } way++; } }else if(!queue1.isEmpty()){ int[] poll = queue1.poll(); //返回队头 if (poll[0] == grid.length - 1 && poll[1] == grid[0].length - 1) return true; int way = 1; for (int[] vector : vectors) { int a = poll[0] + vector[0]; int b = poll[1] + vector[1]; if (a >= 0 && a < grid.length && b >= 0 && b < grid[0].length && visited[a][b] == 0) { int before = grid[poll[0]][poll[1]]; int after = grid[a][b]; if (isOk(before, after, way)) { queue1.offer(new int[]{a, b}); visited[a][b] = 1; break; } } way++; } } } return false; } private boolean isOk(int a, int b, int way) { // way 代表 1, 2, 3, 4 // 分别代表 上 下 左 右 if (way == 1) { if ((a == 2 || a == 5 || a == 6) && (b == 2 || b == 3 || b == 4)) return true; } else if (way == 2) { if ((a == 2 || a == 3 || a == 4) && (b == 2 || b == 5 || b == 6)) return true; } else if (way == 3) { if ((a == 1 || a == 3 || a == 5) && (b == 1 || b == 4 || b == 6)) return true; } else if (way == 4) { if ((a == 1 || a == 4 || a == 6) && ((b == 1 || b == 3 || b == 5))) return true; } return false; } public static void main(String[] args) { Solution s = new Solution(); int[][] grid = {{4,1,3},{6,1,2}}; boolean b = s.hasValidPath(grid); System.out.println(b); } }
可费了我好大劲呢,我这速度,怕是会死在路上。
效率呀效率,得提高呀。
——2020.6.17