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. 单词接龙

题目描述

给定两个单词(beginWordendWord)和一个字典,找到从 beginWordendWord 的最短转换序列的长度。转换需遵循如下规则:

  1. 每次转换只能改变一个字母。
  2. 转换过程中的中间单词必须是字典中的单词。

说明:

  • 如果不存在这样的转换序列,返回 0。
  • 所有单词具有相同的长度。
  • 所有单词只由小写字母组成。
  • 字典中不存在重复的单词。
  • 你可以假设 beginWordendWord 是非空的,且二者不相同。

示例 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 就可以找到从 beginWordendWord 的最短转换序列的长度。

注意,字典中是不包含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 总结的更多相关文章

  1. [LeetCode] BFS解决的题目

    一.130  Surrounded Regions(https://leetcode.com/problems/surrounded-regions/description/) 题目: 解法: 这道题 ...

  2. leetcode BFS解题思路

    Word Ladder 思路一:单向bfs, 使用visited数组记录哪些已经访问过了, 访问过的就不允许再次入队, 同时这里想到的是使用26个英文字母,枚举可能的取值, 类似brute force ...

  3. leetcode BFS

    1. word ladder class Solution { public: int ladderLength(string beginWord, string endWord, unordered ...

  4. [LintCode]——目录

    Yet Another Source Code for LintCode Current Status : 232AC / 289ALL in Language C++, Up to date (20 ...

  5. [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 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. [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 ...

  10. [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 ...

随机推荐

  1. spark 入门教程合集

    看到一篇不错的 spark 入门教程的合集,在此记录一下 http://www.cnblogs.com/shishanyuan/p/4699644.html

  2. 使用阿里云oss

    写这篇博文的原因是公司有个项目需要用到阿里云来存放用户头像文件.后期软件安装版本也可能需要存进去,然后折腾了两天终于摸熟了一点皮毛,在这里给大家简单介绍下. 一.初识对象存储oss 1.进入阿里云控制 ...

  3. Java +支付宝 +接入+最全+最佳-实战-demo

    一.支付宝配置: 1.需要在支付宝商户平台购买支付的产品并开通支付. 2.购买支付产品登录支付宝:https://auth.alipay.com/login/index.htm 3.登录之后首页点击查 ...

  4. TI MSP430工程配置及2019年电赛A题编程示例(使用430 F5529)

    配置 第一步:右击工程,选择Options 第二步:在General Options的Target选项卡里选择对应的器件Device,这里是MSP430G2231 第三步:在Debugger里选择FE ...

  5. TCP/UDP对比总结

    目录 1 TCP-UDP对比 2 UDP介绍 3 TCP介绍 3.1 可靠传输的原理和实现 3.1.1 可靠传输原理 3.1.2 可靠传输实现 3.2 TCP面向连接管理 3.2.1 建立连接 3.2 ...

  6. 神盘GCCX,2019必撸大毛!

    自从今年5月转型投资以来,已经很少薅羊毛了! 不是不撸,是因为一般的羊毛我真看不上! 撸羊毛能不能发财,能不能日入几百几千! 答案是,可以! 干羊毛,像趣步,云钱包,云比特,环保币,很多人都发财了!前 ...

  7. Gitment评论插件的使用

    前言 继上一篇的 GitPages部署自己的网站 现在开始添加博客的评论插件Gitment.这里的话我是使用hexo添加gitment插件,如果不是使用hexo,请到官网指定这里. 开始 第一步 注册 ...

  8. 解决多字段联合逻辑校验问题【享学Spring MVC】

    每篇一句 不要像祥林嫂一样,天天抱怨着生活,日日思考着辞职.得罪点说一句:"沦落"到要跟这样的人共事工作,难道自己身上就没有原因? 前言 本以为洋洋洒洒的把Java/Spring数 ...

  9. 写论文的第四天 Spark安装 使用sparkshell

    Spark分布式安装 Spark安装注意:需要和本机的hadoop版本对应 前往spark选择自己相对应的版本下载之后进行解压 命令:tar –zxf spark-2.4.0-bin-hadoop2. ...

  10. GSS4&&花仔游历各国

    首先呢,我们想到一种数据结构可以区间开方,一看就不行,但是一看就算是10^18开六次方也只剩一,就不用开根了,所以可以想到用线段树或者分块水过,由于本人 不会用分块,只能用常数巨大的线段树 Code ...