【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 ...
随机推荐
- studio无限轮播
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=&q ...
- python基础--列表,元组
list1 = [1,2,3,4,5,6]list2 = ['wang','cong']# 1对列表中的元素取值(通过索引)print(list1[3]) # 4print(list2[1]) # c ...
- (三十三)c#Winform自定义控件-日期控件
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- (二十四)c#Winform自定义控件-单标题窗体
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- Docker进阶-容器监控cAdvisor+InfluxDB+Granfana
概述 前面文章介绍使用docker compose组合应用并利用scale快速对容器进行扩容. 由于docker compose启动的服务都在同一台宿主机上,对于一个宿主机上运行多个容器应用时,容器的 ...
- 多线程编程-synchronized
使用取钱的demo来模拟实现线程的同步 package com.iotec.synchronizedTest; import java.io.ObjectInputStream; public cla ...
- jmeter学习笔记-----第一天
环境简介:apache-jmeter-3.3 win10系统 一.Jmeter录制操作步骤: 1.工作台---添加HTTP代理服务器: 2.为自己笔记本的浏览器设置相同代理: 3.测试计划下-s ...
- Sqlserver2012 评估期已过问题
sql server 2012提示评估期已过的解决方法: 第一步:进入SQL2012配置工具中的安装中心. 第二步:再进入左侧维护选项界面,然后选择选择版本升级. 第三步:进入输入产品密钥界面,输入相 ...
- 弹性布局(display:flex;)属性详解
Flexbox 是 flexible box 的简称(注:意思是“灵活的盒子容器”),是 CSS3 引入的新的布局模式.它决定了元素如何在页面上排列,使它们能在不同的屏幕尺寸和设备下可预测地展现出来. ...
- 《Java 8 in Action》Chapter 3:Lambda表达式
1. Lambda简介 可以把Lambda表达式理解为简洁地表示可传递的匿名函数的一种方式:它没有名称,但它有参数列表.函数主体.返回类型,可能还有一个可以抛出的异常列表. 匿名--我们说匿名,是因为 ...