【LeetCode】BFS 总结
BFS(广度优先搜索) 常用来解决最短路径问题。
第一次便利到目的节点时,所经过的路径是最短路径。
几个要点:
- 只能用来求解无权图的最短路径问题
- 队列:用来存储每一层便利得到的节点
- 标记:对于遍历过的结点,应将其标记,以防重复访问
279. 完全平方数
题目描述
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
解题思路
从 0 到 n 有 n+1 个整数,把这 n+1 个整数看做是节点。如果两个节点之间的差是一个完全平方数,我们就说这两个节点之间是有连接的。通过这个思路我们就可以建立一张图。
找到 n 到 0 的最短路径,我们就找到了 n 至少需要几个完全平方数组成。
public int numSquares(int n) {
List<Integer> squares = generateSquares(n);
Queue<Integer> queue = new LinkedList<>();
boolean[] marked = new boolean[n + 1];
queue.add(n);
marked[n] = true;
int level = 0;
while(!queue.isEmpty()){
int size = queue.size();
level++;
while(size-- >0){
int cur = queue.poll();
for (int s : squares){
int next = cur - s;
if (next < 0)
break;
if (next == 0)
return level;
if (marked[next])
continue;
queue.add(next);
marked[next] = true;
}
}
}
return n;
}
private List<Integer> generateSquares(int n){
List<Integer> squares = new ArrayList<>();
int square = 1;
int diff = 3;
while(square <= n){
squares.add(square);
square += diff;
diff += 2;
}
return squares;
}
127. 单词接龙
题目描述
给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord到 endWord 的最短转换序列的长度。转换需遵循如下规则:
- 每次转换只能改变一个字母。
- 转换过程中的中间单词必须是字典中的单词。
说明:
- 如果不存在这样的转换序列,返回 0。
- 所有单词具有相同的长度。
- 所有单词只由小写字母组成。
- 字典中不存在重复的单词。
- 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
输出: 5
解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5。
示例 2:
输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
输出: 0
解释: endWord "cog" 不在字典中,所以无法进行转换。
解题思路
如果两个单词在对应位置上只有一个字母是不同的,我们就说这两个单词是连接的。按照这个定义,我们可以建立一张图。对这张图进行 BFS 就可以找到从 beginWord 到 endWord 的最短转换序列的长度。
注意,字典中是不包含beginWord的,我们需要将其手动加入再建立图。
public int ladderLength (String beginWord, String endWord, List<String> wordList) {
wordList.add(beginWord); // 手动加入起始单词
int N = wordList.size();
int start = N -1;
int end = 0;
while (end < N && !wordList.get(end).equals(endWord)) {
end++;
}
if (end == N) // 目标单词不在字典中
return 0;
List<Integer>[] graphic = buildGraphic(wordList);
return getShortestPath(graphic,start,end);
}
private List<Integer>[] buildGraphic (List<String> wordList) {
int N = wordList.size();
List<Integer>[] graphic = new List[N];
for (int i = 0; i < N; i++) {
graphic[i] = new ArrayList<>();
for (int j = 0; j < N; j++) {
if (isConnect(wordList.get(i), wordList.get(j))) {
graphic[i].add(j);
}
}
}
return graphic;
}
private boolean isConnect (String s1, String s2) {
int diff = 0;
for (int i = 0; i < s1.length() && diff <= 1; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
diff++;
}
}
return diff == 1;
}
private int getShortestPath (List<Integer>[] graphic, int start, int end) {
Queue<Integer> queue = new LinkedList<>();
boolean[] marked = new boolean[graphic.length];
queue.add(start);
marked[start] = true;
int pathLength = 1;
while (!queue.isEmpty()) {
int size = queue.size();
pathLength++;
while (size-- > 0) {
int cur = queue.poll();
for (int next : graphic[cur]) {
if (next == end) {
return pathLength;
}
if (marked[next]) {
continue;
}
queue.add(next);
marked[next] = true;
}
}
}
return 0;
}
【LeetCode】BFS 总结的更多相关文章
- [LeetCode] BFS解决的题目
一.130 Surrounded Regions(https://leetcode.com/problems/surrounded-regions/description/) 题目: 解法: 这道题 ...
- leetcode BFS解题思路
Word Ladder 思路一:单向bfs, 使用visited数组记录哪些已经访问过了, 访问过的就不允许再次入队, 同时这里想到的是使用26个英文字母,枚举可能的取值, 类似brute force ...
- leetcode BFS
1. word ladder class Solution { public: int ladderLength(string beginWord, string endWord, unordered ...
- [LintCode]——目录
Yet Another Source Code for LintCode Current Status : 232AC / 289ALL in Language C++, Up to date (20 ...
- [LeetCode] 130. Surrounded Regions_Medium tag: DFS/BFS
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A reg ...
- [LeetCode] 849. Maximize Distance to Closest Person_Easy tag: BFS
In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is emp ...
- [LeetCode] 513. Find Bottom Left Tree Value_ Medium tag: BFS
Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...
- [LeetCode] 787. Cheapest Flights Within K Stops_Medium tag: Dynamic Programming, BFS, Heap
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...
- [LeetCode] 821. Shortest Distance to a Character_Easy tag: BFS
Given a string S and a character C, return an array of integers representing the shortest distance f ...
- [LeetCode] 675. Cut Off Trees for Golf Event_Hard tag: BFS
You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-nega ...
随机推荐
- Vector的一些事
1.利用数组对vector进行初始化方法 当然有许多方法,这里就讲一种.原因简单,其他方式请参见这个博文:http://www.cplusplus.me/1112.html , , , , -}; v ...
- WebGL简易教程(二):向着色器传输数据
目录 1. 概述 2. 示例:绘制一个点(改进版) 1) attribute变量 2) uniform变量 3) varying变量 3. 结果 4. 参考 1. 概述 在上一篇教程<WebGL ...
- 使用Qt5+CMake实现图片的区域选择(附源码)
近期研发涉及到了图片的区域选择,找来一些资料一直不能很满意,所以自己实现了一个. 实现步骤如下.源码可以点击ImageAOI获取. 如下资料来自源码的README. ImageAOI (XLabel) ...
- (十九)c#Winform自定义控件-停靠窗体
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- https理论及实践
什么是https协议? http协议以明文的方式在网络中传输,安全性难以保证,https在http协议的基础上加入SSL/TLS层.TLS是SSL协议的最新版本,SSL使用SSL数字证书在通信两端建立 ...
- 为什么说java是只有值传递?
如果你学的第一门程序语言是java可能对这个传递方式没有那么敏感,如果学了c或c++,然后再学java,那么可能对这个问题会感到困惑. 1.值传递与引用传递的概念 在将传递方式之前先理解一下形参与实参 ...
- c# 20160721
ctrl y =>反撤销 ctrl m m 隐藏当前代码段 重载运算符语法 把事件处理程序注册为 click事件的监听程序 [newButton.click+=newButton_click] ...
- [Spring cloud 一步步实现广告系统] 21. 系统错误汇总
广告系统学习过程中问题答疑 博客园 Eureka集群启动报错 Answer 因为Eureka在集群启动过程中,会连接集群中其他的机器进行数据同步,在这个过程中,如果别的服务还没有启动完成,就会出现Co ...
- 一、Ansible入门篇
一.Ansible简介 Ansible是一个自动化运维的工具 基于python语言编写,因此机器需要具备python环境. 通过ssh的连接方式进行自动化部署,ansible优先使用OpenSSH,在 ...
- 使用.Net Core CLI命令dotnet new创建自定义模板
文章起源来自一篇博客:使用 .NET CORE 创建 项目模板,模板项目,Template - DeepThought - 博客园 之前使用Abp的时候就很认同Abp创建模板项目的方式.想不到.Net ...