本文主要是介绍代码随想录图论 第五天| 841.钥匙和房间 463. 岛屿的周长,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码随想录图论 第五天| 841.钥匙和房间
一、 841.钥匙和房间
题目链接:https://leetcode.cn/problems/keys-and-rooms/
思路:钥匙就是索引,遍历过就标记,每拿到一个房间的钥匙,直接for循环递归遍历,深度优先直接拿下。
class Solution {public boolean canVisitAllRooms(List<List<Integer>> rooms) {boolean[] visited = new boolean[rooms.size()];dfs(visited, rooms, 0);for (boolean b : visited) {if (b == false) return false;}return true;}void dfs(boolean[] visited, List<List<Integer>> rooms, int key) {if (visited[key]) return;visited[key] = true;List<Integer> list = rooms.get(key);for (Integer i : list) {dfs(visited, rooms, i);}}
}
二、463. 岛屿的周长
题目链接:https://leetcode.cn/problems/island-perimeter/
思路:常规思路,遍历每一个岛屿并且计算当前点的边长就可以。
class Solution {int sum = 0;public int islandPerimeter(int[][] grid) {for (int i = 0; i < grid.length; i++) {for (int j = 0; j < grid[0].length; j++) {if (grid[i][j] == 1) {dfs(grid, i, j);return sum;}}}return sum;}void dfs(int[][] grid, int x, int y) {if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) {return;}if (grid[x][y] == 2 || grid[x][y] == 0) return;grid[x][y] = 2;if (x-1 < 0 || grid[x-1][y] == 0) sum++;if (x+1 >= grid.length || grid[x+1][y] == 0) sum++;if (y-1 < 0 || grid[x][y-1] == 0) sum++;if (y+1 >= grid[0].length || grid[x][y+1] == 0) sum++;dfs(grid, x-1, y);dfs(grid, x+1, y);dfs(grid, x, y-1);dfs(grid, x, y+1);}
}
这篇关于代码随想录图论 第五天| 841.钥匙和房间 463. 岛屿的周长的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!