提问111111111

为什么n =8 的时候走完if判断后走的是
isTrue[n] = false;//当前第n盏灯是关闭的
dfs(n + 1);
的代码而不是
isTrue[n] = true;//当前第n盏灯是打开的
dfs(n + 1);//递归
的代码

public class t7 {
static int e[][] = new int[8][8];//存储灯管的连通情况
static int fa[] = new int[8];//并查集的父节点
static boolean isTrue[] = new boolean[8];
static int ans = 0;

public static void main(String[] args) {
    //连边建图
    //a b c d e f g
    //1 2 3 4 5 6 7
    //e[i][j]=1表示i灯光和j灯光是相互连接的
    e[1][2] = e[1][6] = 1;
    e[2][1] = e[2][7] = e[2][3] = 1;
    e[3][2] = e[3][4] = e[3][7] = 1;
    e[4][3] = e[4][5] = 1;
    e[5][4] = e[5][6] = e[5][7] = 1;
    e[6][1] = e[6][5] = e[6][7] = 1;
    dfs(1);
    System.out.println(ans);
}

static void dfs(int n) {
    if (n == 8) {//出口,遍历了每一盏灯的情况
        for (int i = 1; i <= 7; i++) {//初始化每一个父节点
            fa[i] = i;
        }
        for (int i = 1; i <= 7; i++) {
            for (int j = 1; j <= 7; j++) {
                if (isTrue[i] && isTrue[j] && e[i][j] == 1) {//如果当前两盏相互连接的灯处于打开的状态则放在一个集合里
                    fa[find(i)] = find(j);//合并操作
                }
            }
        }
        int cnt = 0;//用来记录联通情况
        for (int i = 1; i <= 7; i++) {
            if (isTrue[i] && fa[i] == i) {
                cnt++;
            }
        }
        //当有且仅有一种联通亮灯情况的时候才合法,这个时候ans++
        if (cnt == 1) ans++;
        return;
    }
    isTrue[n] = true;//当前第n盏灯是打开的
    dfs(n + 1);//递归
    isTrue[n] = false;//当前第n盏灯是关闭的
    dfs(n + 1);
}

static int find(int x) {//寻找父节点
    if (x == fa[x]) {
        return x;
    } else {
        fa[x] = find(fa[x]);
        return fa[x];
    }
}

}

递归类型的,建议画一下图,思考一下

完整代码呢?