蓝桥杯 - 七段码 java

题目描述

本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。

小蓝要用七段码数码管来表示一种特殊的文字。

在这里插入图片描述

上图给出了七段码数码管的一个图示,数码管中一共有 77 段可以发光的二 极管,分别标记为 a, b, c, d, e, f, ga,b,c,d,e,f,g

小蓝要选择一部分二极管(至少要有一个)发光来表达字符。在设计字符 的表达时,要求所有发光的二极管是连成一片的。

例如:bb 发光,其他二极管不发光可以用来表达一种字符。

例如 cc 发光,其他二极管不发光可以用来表达一种字符。这种方案与上 一行的方案可以用来表示不同的字符,尽管看上去比较相似。

例如:a, b, c, d, ea,b,c,d,e 发光,f, gf,g 不发光可以用来表达一种字符。

例如:b, fb,f 发光,其他二极管不发光则不能用来表达一种字符,因为发光 的二极管没有连成一片。

请问,小蓝可以用七段码数码管表达多少种不同的字符?

运行限制

  • 最大运行时间:1s
  • 最大运行内存: 128M
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改

public class Main {
    static int count = 0;
    static boolean[][] connected = new boolean[8][8]; //7个数 0不用
    static int[] father = new int[8]; //并查集
    static boolean[] used = new boolean[8]; // 判断是否使用过
    //寻找根节点
    public static int find(int i){
      if(father[i] == i) return i;
      father[i] = find(father[i]);
      return father[i];
    }
    //合并集合
    public static void union(int x, int y){
      int fx = find(x);
      int fy = find(y);
      if(fx != fy) father[fx] = fy;
    }
    //初始化
    public static void initConnect(){
      connected[1][2] = connected[1][6] = true;
      connected[2][1] = connected[2][3] = connected[2][7] = true;
      connected[3][2] = connected[3][4] = connected[3][7] = true;
      connected[4][3] = connected[4][5] = true;
      connected[5][4] = connected[5][6] = connected[5][7] = true;
      connected[6][1] = connected[6][5] = connected[6][7] = true;
      connected[7][2] = connected[7][3] = connected[7][5] = connected[7][6] = true;
    }
    //初始化并查集
    public static void init(){
      for(int i = 1; i <= 7; i++){
        father[i] = i;
      }
    }
    //查找当前存在多少个集合
    public static int collection(){
      int k = 0;
      for(int i = 1; i <= 7; i++){
        if(used[i] && father[i] == i) k++;
      }
      return k;
    }
    //深搜回溯
    public static void dfs(int d){
      if(d > 7){
        init();
        //两层循环遍历
        for(int i = 1; i <= 7; i++){
          for(int j = i; j <= 7; j++){
            //如果发光且相邻,则合并
            if(connected[i][j] && used[i] && used[j]){
              union(i,j);
            }
          }
        }
        //查找存在多少个集合
        if(collection() == 1) count++;
        return;
      }
      //开灯d 
      used[d] = true;
      dfs(d+1);
      //关灯d
      used[d] = false; //回溯
      dfs(d+1);
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        //在此输入您的代码...
        //并查集做法 思路在于将连通的二极管合在一起,判断是否只有一个集合,是则为全连通
        initConnect();
        dfs(1);
        System.out.println(count);
        scan.close();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_51712663/article/details/127115002