//从起点开始后,每遇到一把钥匙,都会同时在该位置以新的状态开启新的广搜,这样会更新之前无法走过的位置
static int N = 35, K = 10, INF = 0x3f3f3f3f;
static int[][][] dist = new int[N][N][1 << K];//拿到不同钥匙到达该位置的最段路径
static int[][] dirs = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
public int shortestPathAllKeys(String[] g) {
int n = g.length, m = g[0].length(), cnt = 0;
Deque<int[]> d = new ArrayDeque<>();
//查找起点,获取钥匙个数
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
Arrays.fill(dist[i][j], INF);
char c = g[i].charAt(j);
if (c == '@') {
d.addLast(new int[]{i, j, 0});
dist[i][j][0] = 0;
} else if (c >= 'a' && c <= 'z') cnt++;
}
}
//广度优先搜索
while (!d.isEmpty()) {
int[] info = d.pollFirst();
int x = info[0], y = info[1], cur = info[2], step = dist[x][y][cur];
for (int[] di : dirs) {
int nx = x + di[0], ny = y + di[1];
if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;//出界
char c = g[nx].charAt(ny);
if (c == '#') continue;//墙
if ((c >= 'A' && c <= 'Z') && (cur >> (c - 'A') & 1) == 0) continue;//没有钥匙
int ncur = cur;
if (c >= 'a' && c <= 'z') ncur |= 1 << (c - 'a');//获取一把钥匙
if (ncur == (1 << cnt) - 1) return step + 1;//已经获取全部钥匙
if (step + 1 >= dist[nx][ny][ncur]) continue;//在拿到部分钥匙的情况下已经走过该位置
dist[nx][ny][ncur] = step + 1;//在拿到部分钥匙的情况下没有走过该位置
d.addLast(new int[]{nx, ny, ncur});
}
}
return -1;
}
2022.11.10-----leetcode.864
最新推荐文章于 2024-10-06 14:10:45 发布