• C++ BFS相关题目


    目录

    图像渲染  

    岛屿数量


    图像渲染  

    733. 图像渲染

     vis就是标记1有没有被用过

    符合条件的都放到队列里,每次出队列一个,判四个,

    如果要改的值与当前的值相同直接返回

    注意:image[x][y] == prev要放在坐标判断的后面,不然会越界,本来想的是不成立先跳出if,不对,这个左边的判段就是为了image[x][y] == prev这个,先后顺序

    1. class Solution {
    2. public:
    3. int dx[4] = {0, 0, 1, -1};
    4. int dy[4] = {1, -1, 0, 0};
    5. vectorint>> floodFill(vectorint>>& image, int sr, int sc, int color) {
    6. if(image[sr][sc] == color) return image;
    7. int m = image.size(), n = image[0].size();
    8. queueint, int>> q;
    9. q.push({sr, sc});
    10. int prev = image[sr][sc];
    11. while(q.size())
    12. {
    13. auto e = q.front(); q.pop();
    14. image[e.first][e.second] = color;
    15. for(int i = 0; i < 4; i++)
    16. {
    17. int x = e.first + dx[i], y = e.second + dy[i];
    18. if(x >= 0 && x < m && y >= 0 && y < n && image[x][y] == prev)
    19. q.push({x, y});
    20. }
    21. }
    22. return image;
    23. }
    24. };

      岛屿数量

     200. 岛屿数量

     

    对每一个位置找联通块,对找过的1进行标记

    错误:因为先是在里面定义的,发现bfs也要用,又在全局定义。。。mn不对,一直不过,第二次这样了

    3.给的是string,传的是char,vs里编不过

    1. class Solution {
    2. public:
    3. vectorbool>> vis;
    4. vector<int> dx = {0, 0, -1, 1};
    5. vector<int> dy = {1, -1, 0, 0};
    6. int m, n;
    7. int numIslands(vectorchar>>& grid) {
    8. //加了int 导致一直不对
    9. m = grid.size(), n = grid[0].size();
    10. vis.resize(m, vector<bool>(n, false));
    11. int ret = 0;
    12. for(int i = 0; i < m; i++)
    13. {
    14. for(int j = 0; j < n; j++)
    15. {
    16. if(grid[i][j] == '1' && !vis[i][j])
    17. {
    18. ret++;
    19. bfs(grid, i, j);
    20. }
    21. }
    22. }
    23. return ret;
    24. }
    25. void bfs(vectorchar>>& grid, int i, int j)
    26. {
    27. queueint, int>> q;
    28. q.push({i, j});
    29. vis[i][j] = true;
    30. while(q.size())
    31. {
    32. auto e = q.front(); q.pop();
    33. for(int i = 0; i < 4; i++)
    34. {
    35. int x = e.first + dx[i], y = e.second + dy[i];
    36. //不写范围保证,会报错
    37. if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' && !vis[x][y])
    38. {
    39. q.push({x, y});
    40. vis[x][y] = true;
    41. }
    42. }
    43. }
    44. }
    45. };
  • 相关阅读:
    Scala基础【常用方法补充、模式匹配】
    【编译原理】类型检查
    ideogram.ai 不同风格的效果图
    Pycharm安装与设置
    java参数传值
    echarts实现3d饼图
    matlab之数组排序的方法和函数
    【LeetCode】C++:数组类算法-运用基础算法思想
    一文浅析机器学习、优化理论、统计分析、数据挖掘、神经网络、人工智能、模式识别之间的关系
    在 Windows 中安装 pgvector
  • 原文地址:https://blog.csdn.net/m0_74922218/article/details/139581979