本文主要是介绍代码随想录图论 第四天| 827.最大人工岛 127. 单词接龙,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码随想录图论 第四天 | 827.最大人工岛 127. 单词接龙
一、827.最大人工岛
题目链接:https://leetcode.cn/problems/making-a-large-island/
思路:
class Solution {int[][] position = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};int dfs(int[][] grid, int x, int y, int mark) {grid[x][y] = mark;int sum = 0;for (int[] ints : position) {int nx = x + ints[0];int ny = y + ints[1];if (nx < 0 || nx >= grid.length || ny < 0 || ny >= grid[0].length)continue;if (grid[nx][ny] == 1) {sum += 1 + dfs(grid, nx, ny, mark);}}return sum;}public int largestIsland(int[][] grid) {int ans = -1, 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++) {if (grid[row][col] != 0) continue;Set<Integer> hashSet = new HashSet<>(); 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]; if (hashSet.contains(curMark) || !getSize.containsKey(curMark)) continue;hashSet.add(curMark);curSize += getSize.get(curMark);}ans = Math.max(ans, curSize);}}return ans == -1 ? size * size : ans;}
}
二、127. 单词接龙
题目链接:https://leetcode.cn/problems/word-ladder/
思路:求最短路径使用广度优先,从第一个字符串开始入队,出队后,把该字符串的每一个位置都从a到z替换,即采用广度优先的思路。
class Solution {public int ladderLength(String beginWord, String endWord, List<String> wordList) {HashSet<String> wordSet = new HashSet<>(wordList);if (wordSet.size() == 0 || !wordSet.contains(endWord)) return 0;HashMap<String, Integer> map = new HashMap<>();Deque<String> queue = new LinkedList<>();queue.add(beginWord);map.put(beginWord, 1);while (!queue.isEmpty()) {String string = queue.remove();Integer path = map.get(string);for (int i = 0; i < string.length(); i++) {char[] chars = string.toCharArray();for (char j = 'a'; j <= 'z'; j++) {chars[i] = j;String curStr = String.valueOf(chars);if (curStr.equals(endWord)) {return path+1;}if (wordSet.contains(curStr) && !map.containsKey(curStr)) {map.put(curStr, path+1);queue.add(curStr);}}}}return 0;}
}
这篇关于代码随想录图论 第四天| 827.最大人工岛 127. 单词接龙的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!