京东笔试 8.19
第三题bfs内存超了 过了90
佬们怎么优化?
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); //构建地图, 0为空地, 1为障碍物 int[][] map = new int[n][m]; int[][] tag = new int[n][m]; for (int i = 0; i < n; i++) { String line = in.next(); for (int j = 0; j < m; j++) { map[i][j] = line.charAt(j) == '.' ? 0 : 1; } } if(map[n - 1][m - 1] == 1){ System.out.println(-1); return; } int step = -1; //广度优先,辅助数组tag,如果tag[i][j] == 2,说明更早的时候来过这里了,就不用再去这里了 LinkedList<int[]> queue = new LinkedList<>(); queue.add(new int[] {0, 0}); while (!queue.isEmpty()) { int s = queue.size(); step++; ArrayList<int[]> list = new ArrayList<>(); while (s-- > 0) { int []temp = queue.poll(); if (temp[0] == n - 1 && temp[1] == m - 1) { System.out.println(step); return; } //三个方向 int k = 1; //没去过,且不为障碍物 while (temp[0] + k < n && tag[temp[0] + k][temp[1]] != 2 && map[temp[0] + k][temp[1]] != 1) { list.add(new int[]{temp[0] + k,temp[1]}); queue.add(new int[] {temp[0] + k, temp[1]}); k++; } k = 1; while (temp[1] + k < m && tag[temp[0]][temp[1] + k] != 2 && map[temp[0]][temp[1] + k] != 1) { list.add(new int[]{temp[0],temp[1] + k}); queue.add(new int[] {temp[0], temp[1] + k}); k++; } k = 1; while (temp[0] + k < n && temp[1] + k < m && tag[temp[0] + k][temp[1] + k] != 2 && map[temp[0] + k][temp[1] + k] != 1) { list.add(new int[]{temp[0] + k,temp[1] + k}); queue.add(new int[] {temp[0] + k, temp[1] + k}); k++; } } for(int[] ints: list){ tag[ints[0]][ints[1]] = 2; } } System.out.println(-1); }