BFS搜索之状态压缩
本题目以 Leetcode.847 为例,简单描述一下状态压缩+BFS
使用状态压缩来表示当前元素是否被访问过,不然就得花费很大的空间去创建数组表示状态,状态压缩使用二进制数来表示 0一般为没被访问,1为被访问,例如 state = 000…101 就表示 0和2这两个点是被访问过的(二进制上的数为1),state 的长度则表示多少个节点。
状态压缩都需要用到位运算,例如需要判断一个点 x 是否被访问,则使用a = (state >> x) & 1 返回 1(已访问) 或是 0(未访问)右移到第x位来跟1做与运算。
就像本题目最多节点 有12个,在java int型32位之下,可以状态压缩。如题:
节点可以重复访问,然后每个节点又可以是起点,所以有很多情况,使用BFS来搜索:
public class solution_847 {
static int INF = -1;
public static int shortestPathLength(int[][] graph) {
int n = graph.length;
int m = 1 << n; //
int[][] dist = new int[m][n];
for (int i = 0; i < m; i++) {
Arrays.fill(dist[i],INF); //将所有点都设为不可达
}
ArrayDeque<int[]> d = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
dist[1<<i][i] = 0; //因为可以从任意点开始出发,每个点的起始距离设置为0
d.addLast(new int[]{1<<i,i});
}
//假设从每个点都是源点,全部遍历一遍
while (!d.isEmpty()){
int[] poll = d.pollFirst();
/*
* 开始BFS搜索,state 用来判断此点是否被访问过
* u 代表点 step 为走的步数
* */
int state = poll[0],u = poll[1],step = dist[state][u];
//判断是否所有点都已经走过
if(state == m - 1){
return step;
}
/*
* graphu[u] 表示与此点连接的其他点
* 单个单个遍历
*
* */
for (int i :
graph[u]) {
if(dist[state | (1 << i)][i] == INF){ //如果这个点没有走过
dist[state | (1 << i)][i] = step + 1;// 设置为走过并且步数加一
d.addLast(new int[]{state | (1<<i),i});//将这个点入队进行下一次bfs
}
}
}
return -1;
}
public static void main(String[] args) {
int[][] graph = {{1},{0,2,4},{1,3,4},{2},{1,2}};
System.out.println(shortestPathLength(graph));
}
}