首页 > 其他分享 >经典数据结构题目-图

经典数据结构题目-图

时间:2024-02-05 23:56:02浏览次数:43  
标签:题目 int numCourses new ++ grid 经典 return 数据结构

200. 岛屿数量

  • 思路

    • 遍历二维数组,遇到等于1的进行计算。同时修改同岛的位置为0,避免重复计算
    • 遍历同岛的位置,可以采用dfs深度优先搜索
  • 代码

        char[][] g;
        public int numIslands(char[][] grid) {
            int sum = 0;
            g = grid;
            for(int i = 0; i < grid.length; i ++){
                for(int j = 0; j < grid[0].length; j++){
                    if(grid[i][j] == '1'){
                        sink(i,j);
                        sum ++;
                    }
                }
            }
            return sum;
        }
    		
    		// dfs 检查同岛的位置
        public void sink(int i, int j){
            if(i < 0 || j < 0 || i >= g.length || j >= g[0].length || g[i][j] == '0') return;
            g[i][j] = '0'; // 注意点一
            sink(i + 1, j);
            sink(i, j + 1);
            sink(i - 1, j);
            sink(i, j - 1);
        }
    
  • 注意点

    • 注意点一:已经计数过的岛屿,要将为0/2,避免重复计算
  • 扩展

    • 相似的dfs可以用来计算岛的面积

    • public int maxAreaOfIsland(int[][] grid) {
          int res = 0;
          for (int r = 0; r < grid.length; r++) {
              for (int c = 0; c < grid[0].length; c++) {
                  if (grid[r][c] == 1) {
                      int a = area(grid, r, c);
                      res = Math.max(res, a);
                  }
              }
          }
          return res;
      }
      
      // 计算面积
      int area(int[][] grid, int r, int c) {
          if (!inArea(grid, r, c)) {
              return 0;
          }
          if (grid[r][c] != 1) {
              return 0;
          }
          grid[r][c] = 2;
          
          return 1 
              + area(grid, r - 1, c)
              + area(grid, r + 1, c)
              + area(grid, r, c - 1)
              + area(grid, r, c + 1);
      }
      
      // 判断是否在网格内
      boolean inArea(int[][] grid, int r, int c) {
          return 0 <= r && r < grid.length 
              	&& 0 <= c && c < grid[0].length;
      }
      
    • 参考题解

    • https://leetcode.cn/problems/number-of-islands/solutions/211211/dao-yu-lei-wen-ti-de-tong-yong-jie-fa-dfs-bian-li-

207. 课程表

  • 思路
    • 遍历每一个课程,使用dfs检查每一个课程是否有成环
    • dfs检查课程,需要借助一个flags数组存储每个课程被学习的情况,区分出课程是否被学习、是否在当前课程的学习路线上
      • 0。未学习
      • -1。在其他课程学习路线上学习了。
      • 1。当前课程学习路线上
  • 代码
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        // 将关联的课程放在一起
        Map<Integer,List<Integer>> relatedMap = new HashMap<>();
        for(int i = 0; i < prerequisites.length; i ++){
            List<Integer> related = relatedMap.getOrDefault(prerequisites[i][1],new ArrayList<>());
            related.add(prerequisites[i][0]);
            relatedMap.put(prerequisites[i][1],related);
        }
        int[] flags = new int[numCourses];
        // 判断每个课程的学习会不会成环
        for(int i = 0; i < numCourses; i++){
            if(!dfs(relatedMap,flags,i)){
                return false;
            }
        }
        return true;
    }

    public boolean dfs(Map<Integer,List<Integer>> relatedMap, int[] flags, int num){
        if(flags[num] == 1){ //注意点一
            return false;
        }
        if(flags[num] == -1){
            return true;
        }
        flags[num] = 1;
        if(relatedMap.containsKey(num)){
            for(Integer related : relatedMap.get(num)){
                if(!dfs(relatedMap,flags,related)){
                    return false;
                }
            }
        }
        flags[num] = -1;
        return true;
    }
  • 注意点
    • 注意点一。学习路线上遇到1的课程,说明已经学习路线成环了

210. 课程表 II

  • 思路

    • 使用拓扑排序算法。可以讲图的依赖路线转化成二维数组

    • 需要借助两个数据结构

      • 入度数组。每个节点的前驱节点个数。为0说明当前节点依赖项
      • 邻接表。每个节点的后继节点。
    • 从入度为0的节点开始检查,为0可以加入到结果中,根据领接表找到后继节点,入度-1。循环检查入度为0的节点

  • 代码

    public int[] findOrder(int numCourses, int[][] prerequisites) {
        // 构建入度数组和邻接表
        HashSet<Integer>[] relations = new HashSet[numCourses];
        int[] inDegree = new int[numCourses];
        for(int i = 0; i < numCourses; i++){
            relations[i] = new HashSet<>();
        }
        for(int[] realtion : prerequisites){
            int front = realtion[1];
            int end = realtion[0];
            relations[front].add(end);
            inDegree[end] ++;
        }
        int[] res = new int[numCourses];
        int count = 0;
        
        // 循环处理入度0的节点
        Queue<Integer> queue = new LinkedList<>();
        for(int i = 0; i < numCourses; i++){
            if(inDegree[i] == 0){
                queue.offer(i);
            }
        }
        while(!queue.isEmpty()){
            Integer curr = queue.poll();
            res[count++] = curr;
            for(Integer relation : relations[curr]){
                // 扣除后继节点的入度后,为0继续加入到队列
                inDegree[relation]--;
                if(inDegree[relation] == 0){
                    queue.offer(relation);
                }
            }
        }
        if(count == numCourses){
            return res;
        }
        return new int[0];
        
    }

标签:题目,int,numCourses,new,++,grid,经典,return,数据结构
From: https://www.cnblogs.com/gg12138/p/18009025

相关文章

  • 有关各种数据结构模板
    FHQ-Treap模板题-普通平衡树#include<bits/stdc++.h>#definelstr[u].l#definerstr[u].rusingnamespacestd;constintN=3e5+10;structNode{intl,r;intkey,v;intsize;}tr[N];introot,idx;intn,m;voidpushup(intu){tr[u].size......
  • 2.1 不会有人数据结构比我还菜吧?
    记录三道自己菜死了的与根号有关的题。其中每道题都有polylog解法。题目名称太长了,就不放了。CF1017GTheTree根号做法:考虑操作分块,然后建虚树。建出虚树之后我们就发现很好处理了。同样的,处理每一个块结束后的真实形态,也可以借助这个虚树。总的来说,需要暴力维护一下每个虚......
  • 面试经典 150 题 (十一)
    classSolution{publicintjump(int[]nums){if(nums.length<=1)return0;//记录每次起跳所能跳到的最远的距离intfarestIndex=0;intmaxIndex=0;intstart=0;inttimes=0;while(true){......
  • 面试经典 150 题 (十)
    用一个变量存放当前所能到达的最远的下标位置classSolution{publicbooleancanJump(int[]nums){intfarestIndex=0;//记录当前最远能到达的下标for(inti=0;i<=farestIndex&&i<nums.length;i++){if((nums[i]+i)>......
  • 面试经典 150 题 (九)
    动态规划,五种状态,关键是找出状态转移式classSolution{publicintmaxProfit(int[]prices){intbuy1=-prices[0];intsell1=0;intbuy2=-prices[0];intsell2=0;for(inti=1;i<prices.length;i++......
  • (python)做题记录||2024.2.4||题目是codewars的【 All Balanced Parentheses】
    题目链接:https://www.codewars.com/kata/5426d7a2c2c7784365000783/python我的解决方案:defbalanced_parens(n):#Yourcodehere!used_l=[Falseforiinrange(n)]used_r=[Falseforiinrange(n)]answers=[]defprocess(answer):iflen(a......
  • 数据结构(一)单链表---以题为例
    实现一个单链表,链表初始为空,支持三种操作:向链表头插入一个数;删除第 k 个插入的数后面的数;在第 k 个插入的数后插入一个数。现在要对该链表进行 M 次操作,进行完所有操作后,从头到尾输出整个链表。注意:题目中第 k 个插入的数并不是指当前链表的第 k 个数。例如操作......
  • 数据结构之——数组
    数组数据结构的基本类型之一,它可以构成其他数据结构,如栈、队列、哈希表、树、图、堆、矩阵、张量。数组在内存中的存储方式为一片连续的内存空间,其基本操作与其他数据结构一致,即所谓的增删改查。废话不多说,上代码加以理解。Java类型实现classarray{publicstaticvoid......
  • redis有5种数据结构
    redis有5种数据结构,分别如下:5种数据结构python语言对5种数据结构的增删改查全局函数1|0redis连接importredispool=redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)r=redis.Redis(connection_pool=pool)redis取出的结果默认是字节,可......
  • (python)代码学习||2024.2.3||题目是codewars上的【Validate Sudoku with size `NxN`
    题目的要求是写一个Sudoku类,类中要有一个实例函数判断传给对象的二维数组是否符合数独规则题目链接:https://www.codewars.com/kata/540afbe2dc9f615d5e000425/python下面是写完题后看到的别人的解决方法fromitertoolsimportchainclassSudoku(object):def__init__......