【刷题笔记N1】- 图:岛屿、课程表

刷题笔记系列

【刷题笔记01】- 数组
【刷题笔记02】-链表
【刷题笔记03 -哈希表】
【刷题笔记04】- 字符串
【刷题笔记05】-栈与队列
【刷题笔记06】树


1.岛屿数量

https://leetcode.cn/problems/number-of-islands/description/

  • 思路: DFS 和 BFS
  • 代码
    DFS
class Solution {
    public int numIslands(char[][] grid) {
        int result = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == '1'){
                    mergerLand(grid, i , j);
                    result++;
                }
            }
        }
        return result;
    }

    void mergerLand(char[][] grid, int r, int c) {
    // 判断是否继续处理该“节点”
    if (!inArea(grid, r, c) || grid[r][c] == '0') {
        return;
    }
    grid[r][c] = '0'; 
    // 访问上、下、左、右四个相邻结点
    mergerLand(grid, r - 1, c);
    mergerLand(grid, r + 1, c);
    mergerLand(grid, r, c - 1);
    mergerLand(grid, r, c + 1);
    }

   // 判断坐标 (r, c) 是否在网格中
    boolean inArea(char[][] grid, int r, int c) {
    return 0 <= r && r < grid.length 
        	&& 0 <= c && c < grid[0].length;
    }
}

BFS需要借助队列

public class PositionNode {
    public int x;
    public int y;

    public PositionNode(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public PositionNode() {
    }
}

public class BFS {
    int[][] direct = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    Queue<PositionNode> queue = new LinkedList<>();
    boolean[][] visited;
    int count = 0;

    public int numIslands(char[][] grid) {
        if (grid.length == 0)
            return 0;
        visited = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++){
            for (int j = 0; j < grid[0].length; j++) {
                if (!visited[i][j] && grid[i][j] == '1'){
                    count++;
                    bfs(grid, i, j);
                }
            }
        }
        return count;
    }

    public void bfs(char[][] graph, int x, int y) {
        queue.offer(new PositionNode(x, y));
        visited[x][y] = true;
        while (!queue.isEmpty()) {
            PositionNode cur = queue.poll();
            visited[cur.x][cur.y] = true;
            for (int i = 0; i < 4; i++) {
                PositionNode next = new PositionNode();
                next.x = cur.x + direct[i][0];
                next.y = cur.y + direct[i][1];
                if (next.x < 0 || next.x >= graph.length || next.y < 0 || next.y >= graph[0].length)
                    continue;
                if(!visited[next.x][next.y] && graph[next.x][next.y] == '1'){
                    queue.offer(next);
                    visited[next.x][next.y] = true;
                }
            }
        }
    }
}

这两种写法对于边界处理 和 count岛屿数量的时机都是类似的,区别只在于对节点的访问处理顺序。

2、 LeetCode207 课程表

https://leetcode.cn/problems/course-schedule/description/

class Solution {
    public final static int Not_Search = 0;
    public final static int In_Search = 1;
    public final static int Finish_Search = 2;
    List<List<Integer>> edges = new ArrayList<>();
    int[] searchFlag;
    boolean result = true; // 只有存在环的情况(会在dfs中处理)不能达成拓扑,所以默认为true
    
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        searchFlag = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            edges.add(new ArrayList<>());
        }
        for (int[] value : prerequisites) {
            // edges[i]存的是依赖节点i的节点们
            edges.get(value[1]).add(value[0]);
        }
        for (int i = 0; i < numCourses; i++) {
            if (searchFlag[i] == Not_Search) {
                dfs(i, prerequisites);
            }
        }
        return result;
    }

    public void dfs(int index, int[][] prerequisites) {
        searchFlag[index] = In_Search;
        for (int node : edges.get(index)) {
            if (searchFlag[node] == Not_Search){
                dfs(node, prerequisites);
                if(!result){
                    return;
                }
            } else if (searchFlag[node] == In_Search) {
                result = false;
                return;
            }
        }
        searchFlag[index] = Finish_Search;
    }
}

主要分两步:
梳理出prerequisites中表达的节点依赖关系,用一个便于做数据处理的数据结构存储(此处用的是List<List>)
对节点进行DFS,for循环处理和该节点有依赖关系的节点(通过一个visited数组标记访问情况,如果处理中状态的节点再次被访问,说明存在环,无法形成课程表学习顺序的拓扑序列)

3、 LeetCode210 课程表II

https://leetcode.cn/problems/course-schedule-ii/description/

public class L210_Courses2 {

    List<List<Integer>> edges = new ArrayList<>();
    Stack<Integer> sequence = new Stack<>();
    int[] visited;
    // 判断有向图中是否有环
    boolean valid = true;
    ArrayList<Integer> result;

    public int[] findOrder(int numCourses, int[][] prerequisites) {
        visited = new int[numCourses];
        result = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            edges.add(new ArrayList<>());
        }
        for (int[] nodes : prerequisites) {
            // edges.get(nodes[1]).add(nodes[0])的情况:
            // edges[index] index就是当前处理节点,edges[index]就是依赖于它的节点,
            // 我们的处理是根据 index 取出依赖它的节点们依次去dfs
            // 启动dfs的顺序刚好符合其拓扑顺序的结果,完成dfs的结果则刚好相反,所以结果的存储用栈的思路
            // 但是edges.get(nodes[0]).add(nodes[1])就刚好相反,index就是当前处理节点,edges[index]是它依赖的节点
            // 刚好是它依赖的节点先完成dfs,所以按顺序存就行了
            edges.get(nodes[0]).add(nodes[1]);
        }
        for (int i = 0; i < numCourses && valid; i++) {
            // 为什么不会出现序列重复的问题(5依赖4、3;4依赖3;得出34534),因为在启动dfs时只处理未访问过的节点。
            if (visited[i] == 0) {
                dfs(i);
            }
        }
        return result.stream().mapToInt(Integer::intValue).toArray();
    }
    public void dfs(int index) {
        visited[index] = 1;
        for (int node : edges.get(index)) {
            if (visited[node] == 0){
                dfs(node);// 注意别打错了,这里进去的是node不是index
            } else if (visited[node] == 1) {
                valid = false;
                result.clear();
                return;
            }
        }
        visited[index] = 2;
        result.add(index);
    }
}

和课程表那个题其实只多了一个存结果的处理。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值