Java Solution  | Bitmask |
\nclass Solution {\n    public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n         \n        \n       ArrayList<Integer>[] graph = (ArrayList<
```\nclass Solution {\n    public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n         \n        \n       ArrayList<Integer>[] graph = (ArrayList<Integer>[]) new ArrayList[n];\n       for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n        \n         for(int i=0;i<edges.length;i++)\n         {\n             int u = edges[i][0];\n             int v = edges[i][1];\n             \n             --u;\n             --v;\n             \n             graph[u].add(v);\n             graph[v].add(u);\n         }\n        \n         int[] darr = new int[n-1];\n        \n         for(int mask=0;mask<(1<<(n));mask++)\n         {\n             int d = getmax(mask , graph);\n             \n             if(d>0)\n             {\n                 darr[d-1]++;\n             }\n         }\n        \n        return darr;\n         \n    }\n    \n   int getmax(int mask , ArrayList<Integer>[] graph)\n    {\n          \n          int maxd = -1;\n        \n          for(int i=0;i<15;i++)\n          {      \n              if( (mask & (1<<i)) !=0)\n              {\n                  maxd = Math.max(maxd , dfs(i , graph , mask));\n              }\n          }\n        \n        return maxd;\n    }\n    \n    int dfs(int node , ArrayList<Integer>[] graph , int mask)\n    {\n        \n        \n      Queue<Integer> q\n            = new LinkedList<>();\n        q.add(node);\n        int dist = -1;\n        int curr = mask;\n        \n        while(!q.isEmpty())\n        {\n           dist++;\n        \n         for(int l=q.size()-1;l>=0;l--) {   \n            int z1 = q.peek();\n            curr = curr ^ (1<<z1);\n            q.remove();\n            \n            for(int z : graph[z1])\n            {\n               if(((mask & (1<<z))!=0) && ((curr & (1<<z))!=0))\n               {  \n                  q.add(z); }\n            }\n         }\n                  \n        }\n        \n        if(curr!=0)\n        {\n            return -1;\n        }\n        \n        return dist;\n       \n    }\n}\n```
['Bitmask', 'Java']