Merge pull request #1917 from StriveDD/master

添加0127.单词接龙的Java版本双向BFS代码,0827.最大人工岛的Java版本,0841.钥匙和房间的Java版本的BFS代码
This commit is contained in:
程序员Carl
2023-03-05 20:15:59 +08:00
committed by GitHub
3 changed files with 175 additions and 1 deletions

View File

@ -16,7 +16,7 @@
* 转换过程中的中间单词必须是字典 wordList 中的单词。
* 给你两个单词 beginWord 和 endWord 和一个字典 wordList 找到从 beginWord 到 endWord 的 最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回 0。
 
示例 1
* 输入beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
@ -134,7 +134,70 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
}
```
```java
// Java 双向BFS
class Solution {
// 判断单词之间是否之差了一个字母
public boolean isValid(String currentWord, String chooseWord) {
int count = 0;
for (int i = 0; i < currentWord.length(); i++)
if (currentWord.charAt(i) != chooseWord.charAt(i)) ++count;
return count == 1;
}
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
if (!wordList.contains(endWord)) return 0; // 如果 endWord 不在 wordList 中,那么无法成功转换,返回 0
// ansLeft 记录从 beginWord 开始 BFS 时能组成的单词数目
// ansRight 记录从 endWord 开始 BFS 时能组成的单词数目
int ansLeft = 0, ansRight = 0;
// queueLeft 表示从 beginWord 开始 BFS 时使用的队列
// queueRight 表示从 endWord 开始 BFS 时使用的队列
Queue<String> queueLeft = new ArrayDeque<>(), queueRight = new ArrayDeque<>();
queueLeft.add(beginWord);
queueRight.add(endWord);
// 从 beginWord 开始 BFS 时把遍历到的节点存入 hashSetLeft 中
// 从 endWord 开始 BFS 时把遍历到的节点存入 hashSetRight 中
Set<String> hashSetLeft = new HashSet<>(), hashSetRight = new HashSet<>();
hashSetLeft.add(beginWord);
hashSetRight.add(endWord);
// 只要有一个队列为空,说明 beginWord 无法转换到 endWord
while (!queueLeft.isEmpty() && !queueRight.isEmpty()) {
++ansLeft;
int size = queueLeft.size();
for (int i = 0; i < size; i++) {
String currentWord = queueLeft.poll();
// 只要 hashSetRight 中存在 currentWord说明从 currentWord 可以转换到 endWord
if (hashSetRight.contains(currentWord)) return ansRight + ansLeft;
for (String chooseWord : wordList) {
if (hashSetLeft.contains(chooseWord) || !isValid(currentWord, chooseWord)) continue;
hashSetLeft.add(chooseWord);
queueLeft.add(chooseWord);
}
}
++ansRight;
size = queueRight.size();
for (int i = 0; i < size; i++) {
String currentWord = queueRight.poll();
// 只要 hashSetLeft 中存在 currentWord说明从 currentWord 可以转换到 beginWord
if (hashSetLeft.contains(currentWord)) return ansLeft + ansRight;
for (String chooseWord : wordList) {
if (hashSetRight.contains(chooseWord) || !isValid(currentWord, chooseWord)) continue;
hashSetRight.add(chooseWord);
queueRight.add(chooseWord);
}
}
}
return 0;
}
}
```
## Python
```
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
@ -301,3 +364,4 @@ function diffonechar(word1: string, word2: string): boolean {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -219,7 +219,71 @@ public:
};
```
# 其他语言版本
## Java
```Java
class Solution {
private static final int[][] position = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // 四个方向
/**
* @param grid 矩阵数组
* @param row 当前遍历的节点的行号
* @param col 当前遍历的节点的列号
* @param mark 当前区域的标记
* @return 返回当前区域内 1 的数量
*/
public int dfs(int[][] grid, int row, int col, int mark) {
int ans = 0;
grid[row][col] = mark;
for (int[] current: position) {
int curRow = row + current[0], curCol = col + current[1];
if (curRow < 0 || curRow >= grid.length || curCol < 0 || curCol >= grid.length) continue; // 越界
if (grid[curRow][curCol] == 1)
ans += 1 + dfs(grid, curRow, curCol, mark);
}
return ans;
}
public int largestIsland(int[][] grid) {
int ans = Integer.MIN_VALUE, size = grid.length, mark = 2;
Map<Integer, Integer> getSize = new HashMap<>();
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (grid[row][col] == 1) {
int areaSize = 1 + dfs(grid, row, col, mark);
getSize.put(mark++, areaSize);
}
}
}
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
// 当前位置如果不是 0 那么直接跳过,因为我们只能把 0 变成 1
if (grid[row][col] != 0) continue;
Set<Integer> hashSet = new HashSet<>(); // 防止同一个区域被重复计算
// 计算从当前位置开始获取的 1 的数量,初始化 1 是因为把当前位置的 0 转换成了 1
int curSize = 1;
for (int[] current: position) {
int curRow = row + current[0], curCol = col + current[1];
if (curRow < 0 || curRow >= grid.length || curCol < 0 || curCol >= grid.length) continue;
int curMark = grid[curRow][curCol]; // 获取对应位置的标记
// 如果标记存在 hashSet 中说明该标记被记录过一次,如果不存在 getSize 中说明该标记是无效标记(此时 curMark = 0)
if (hashSet.contains(curMark) || !getSize.containsKey(curMark)) continue;
hashSet.add(curMark);
curSize += getSize.get(curMark);
}
ans = Math.max(ans, curSize);
}
}
// 当 ans == Integer.MIN_VALUE 说明矩阵数组中不存在 0全都是有效区域返回数组大小即可
return ans == Integer.MIN_VALUE ? size * size : ans;
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -275,6 +275,52 @@ class Solution {
}
```
```Java
// 广度优先搜索
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
boolean[] visited = new boolean[rooms.size()]; // 用一个 visited 数据记录房间是否被访问
visited[0] = true;
Queue<Integer> queue = new ArrayDeque<>();
queue.add(0); // 第 0 个房间标记为已访问
while (!queue.isEmpty()) {
int curKey = queue.poll();
for (int key: rooms.get(curKey)) {
if (visited[key]) continue;
visited[key] = true;
queue.add(key);
}
}
for (boolean key: visited)
if (!key) return false;
return true;
}
}
```
```java
// 广度优先遍历(时间优化)
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int count = 1; // 用来记录可以被访问的房间数目,因为初始状态下 0 号房间可以被访问,所以置为 1
boolean[] visited = new boolean[rooms.size()]; // 用一个 visited 数据记录房间是否被访问
visited[0] = true; // 第 0 个房间标记为已访问
Queue<Integer> queue = new ArrayDeque<>();
queue.add(0);
while (!queue.isEmpty()) {
int curKey = queue.poll();
for (int key: rooms.get(curKey)) {
if (visited[key]) continue;
++count; // 每访问一个访问房间就让 count 加 1
visited[key] = true;
queue.add(key);
}
}
return count == rooms.size(); // 如果 count 等于房间数目,表示能进入所有房间,反之不能
}
}
```
### python3
```python