第三题核心代码: // 从终点开始BFS // 记录每个步数的频率 Map<Integer, Integer> t = new HashMap<>(); int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; boolean[][] visit = new boolean[n][m]; Queue<int[]> q = new LinkedList<>(); q.offer(new int[]{ex, ey, 0}); visit[ex][ey] = true; while (!q.isEmpty()) { int[] cur = q.poll(); int x = cur[0], y = cur[1], dis = cur[2]; // 访问当前节点并更新频率 t.put(dis, t.getOrDefault(dis, 0) + 1); // 四个方向探查 for (int[] dir : dirs) { int nx = x + dir[0], ny = y + dir[1]; if (0 <= nx && nx < n && 0 <= ny && ny < m && !visit[nx][ny] && map[nx][ny] != '1') { // 可以前进 q.offer(new int[]{nx, ny, dis + 1}); visit[nx][ny] = true; } } }
1 1

相关推荐

点赞 评论 收藏
分享
10-20 17:44
新疆大学 C++
点赞 评论 收藏
分享
牛客网
牛客企业服务