AcWing 1491. 圆桌座位Java

文章介绍了如何通过递归实现一个深度优先搜索算法来解决给定的朋友关系和座位限制下,找到满足条件的座位安排方案数量的问题。
摘要由CSDN通过智能技术生成

//分析:是将当前节点的下一节点放入递归或者栈中,全部搜索完8个人才算一种方案
//层数较少可使用递归深搜
//访问状态数组,关系数组,座位数组(该座位谁坐)
//返回值为方案数,当搜索到最后一个座位如果和前一个是朋友返回0;否则只有一种方案(只剩一个人未安)再横向寻找其他可能


import java.util.Scanner;
public class yuanzhuozuowei {
    static int n;
    static int m;
    static int friend[][];
    static boolean st[];
    static int seat[];
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        st = new boolean[n + 1];
        friend = new int[n + 1][n + 1];
        seat = new int[n + 1];// 某个座位上坐第几个人
        for (int i = 0; i < m; i++) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            friend[a][b] = 1;
            friend[b][a] = 1;
        }
        seat[0] = 1;
        st[1] = true;
        System.out.println(dfs(1));

    }

    private static int dfs(int b) {

        // TODO Auto-generated method stub
        if (b == n) {
            if (friend[seat[b - 1]][seat[0]] != 1)
                return 1;
            else
                return 0;
        }
        int res = 0;
        for (int i = 1; i <= n; i++)// n个人
        {
            if (!st[i] && friend[i][seat[b - 1]] != 1)// 符合条件更换主角
            {
                seat[b] = i;// 更换主角(此时参照物改变)
                st[i] = true;
                res += dfs(b + 1);
                st[i] = false;
            }
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值