代码随想录图论 第五天| 841.钥匙和房间
一、 841.钥匙和房间
题目链接:https://leetcode.cn/problems/keys-and-rooms/
思路:钥匙就是索引,遍历过就标记,每拿到一个房间的钥匙,直接for循环递归遍历,深度优先直接拿下。
java
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/
思路:常规思路,遍历每一个岛屿并且计算当前点的边长就可以。
java
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);
}
}