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. 如何搭建环境---初识mybatis

    一:mybatis概念1:简介       MyBatis本是apache的一个开源项目iBatis,2010年改名为 MyBatis,       MyBatis 是一个基于Java的持久层框架.( ...

  2. 实现API优先设计的重要性和实现方式

    应用API优先的方法意味着设计API时,使其具有一致性和适应性,无论应用于哪些开发项目.对API使用API​​描述语言(如OpenAPI)是关键,因为它有助于建立API与其他程序通信的枢纽,即使这些系 ...

  3. 记一次mysql数据库失而复得过程

    背景: 由于是自己买的vps搭建的博客,用的是军哥的一键lnmp源码编译安装的,文章也就几篇,对备份并不太重视,想着等服务器快到期的时候备份一下不就行了. 后来在该服务器上测试lnmp分别编译编译安装 ...

  4. threejs 学习之

    主要内容: 使用 threejs 创建 20x20 的网格,鼠标移动时,方块跟随移动,点击时在网格任意位置放置方块,按 shift 时,删除当前位置方块. 流程如下: 创建网格 创建一个与网格同样尺寸 ...

  5. PHP 数组转字符串后仍保留数组格式

    写此方法的目的是,我想把一个PHP数组配置文件读进程序,添加些配置,然后在写入文件: var_export 方法会把原来的配置打乱(比如数组序号我没有加,他自动给我加上 0,1,2,3...),而且格 ...

  6. web项目jsp中无法引入js问题

    https://blog.csdn.net/C1042135353/article/details/80274685#commentBox 这篇文章超赞的,几个小时的时间看了这篇文章豁然开朗,瞬间懂了 ...

  7. 弹性布局(display:flex;)属性详解

    Flexbox 是 flexible box 的简称(注:意思是“灵活的盒子容器”),是 CSS3 引入的新的布局模式.它决定了元素如何在页面上排列,使它们能在不同的屏幕尺寸和设备下可预测地展现出来. ...

  8. v语言怎么玩

    直接上github: https://github.com/vlang/v 前戏 大概是在6月份的时候,在github上看到了这个玩意,我以为是??? 我下意识的去查了一下有没有人在讨论这个语言,但是 ...

  9. JavaScript中一个方法同时发送两个ajax请求问题

    今天在做项目中遇到一个问题,大概是在一个jsp页面同时有一个select下拉搜索条件框和一个Bootstrap表格展示列表.这两个都要通过ajax向后台拿数据,而且要在页面加载时完成.当时的做法是: ...

  10. 在linux系统中配置NVMe over TCP

    1. 准备环境 1.1 准备linux系统 要求的linux系统可以是运行在物理机上,也可以是虚拟机上: 建议有个linux系统,一个做host,一个做target,如果资源紧张也可以把host和ta ...