310. Minimum Height Trees

For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.

Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).

You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

Example 1 :

Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3 

Output: [1]
Example 2 :

Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
      \ | /
        3
        |
        4
        |
        5 

Output: [3, 4]
Note:

According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-height-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

要找的节点是这个多叉树里面的最长路径的中间一个或两个节点,用多源bfs算法,首先找到所有边缘的节点,即入度为零的节点,然后每次遍历都把剩下的边缘节点都删除掉,删除到最后,就是我们的要的节点。

class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        boolean dp[][] = new boolean[n][n];

        List <Integer> ans = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                dp[i][j] = false;
            }
            ans.add(i);
        }
        if (ans.size() <= 2) {
            return ans;
        }
        // 计算所有节点的入度
        int[] count = new int[n];
        for (int i = 0; i < edges.length; i++) {
            dp[edges[i][0]][edges[i][1]] = true;
            dp[edges[i][1]][edges[i][0]] = true;
            count[edges[i][0]]++;
            count[edges[i][1]]++;
        }
        // 找到入度为1的边缘节点
        List<Integer> inter = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (count[i] == 1) {
                inter.add(i);
            }
        }

        while (!inter.isEmpty()) {
            for (int i : inter) {
                for (int j = 0; j < n; j++) {
                    if (dp[i][j]) {
                        count[j]--;
                    }
                }
                count[i]--;
                ans.remove((Integer) i);
            }

            inter.clear();
            for (int j = 0; j < n; j++) {
                if (count[j] == 1) {
                    inter.add(j);
                }
            }
            if (ans.size() <= 2) {
                return ans;
            }
        }
        return ans;
    }
}

 

### 使用 JavaScript 制作迷宫游戏的核心概念 制作基于 JavaScript 的迷宫游戏涉及多个方面的编程技术,包括但不限于算法设计、图形渲染以及交互逻辑实现。以下是几个关键部分及其相关内容: #### 迷宫生成算法 迷宫的生成通常依赖于特定的图论算法来构建连通路径并确保复杂度适中。常见的迷宫生成方法有深度优先搜索 (DFS)[^1] 和 Prim 算法[^2]。 - **深度优先搜索 (DFS)** DFS 是一种递归遍历树或图的方法,在迷宫生成中的应用可以随机选择起点,并通过标记已访问节点的方式逐步扩展未探索区域直到整个网格被覆盖。 - **Prim 算法** 类似最小生成树的概念,该算法从单个单元格开始,每次向当前集合添加一个新的相邻单元格,直至所有可用空间连接完毕。 ```javascript function generateMaze(width, height) { const maze = Array.from({ length: width }, () => Array(height).fill(0)); function dfs(x, y){ let directions = [[-2,0],[2,0],[0,-2],[0,2]]; shuffle(directions); for(let [dx, dy] of directions){ let nx = x + dx; let ny = y + dy; if(nx >=0 && nx <width && ny>=0 && ny<height && maze[nx][ny]==0 ){ maze[x+dx/2][y+dy/2]=1; // knock down wall between cells. maze[nx][ny]=1; dfs(nx,ny); } } } maze[Math.floor(Math.random()*width)][Math.floor(Math.random()*height)] = 1; dfs(...findRandomStart(maze)); return maze; } ``` #### 渲染与显示 一旦有了数据结构表示的迷宫布局,则需借助 HTML Canvas 或 SVG 技术将其可视化呈现给玩家。Canvas 提供了灵活高效的绘图接口适合实时更新场景;而 SVG 更擅长处理矢量图形尤其当需要精确控制线条粗细颜色等属性时显得尤为有用[^3]。 ```html <canvas id="mazeCanvas"></canvas> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', ()=>{ let canvas = document.getElementById('mazeCanvas'); //... setup context and draw the generated maze here ... }); </script> ``` #### 用户互动机制 为了让游戏更具吸引力还需要加入键盘或者鼠标操作支持让角色能够在迷宫内部移动寻找出口。这一步骤涉及到监听事件绑定动作响应函数等内容[^4]。 ```javascript window.addEventListener("keydown", movePlayer); function movePlayer(event){ switch(event.key){ case 'ArrowUp': player.y--; break; case 'ArrowDown': player.y++; break; case 'ArrowLeft': player.x--; break; case 'ArrowRight': player.x++; break; default: return;// ignore other keys } if(checkCollision(player)){ alert("Game Over!"); }else{ updatePositionOnScreen(); checkWinCondition(); } } ``` [^1]: 关于深度优先搜索的具体描述可参阅相关计算机科学教材章节。 [^2]: Prim's Algorithm details are available in graph theory resources discussing minimum spanning trees. [^3]: For more information on using HTML5 Canvas API see official documentation or tutorials online. [^4]: Event handling basics covered extensively across web development guides.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值