zoukankan      html  css  js  c++  java
  • 200. 岛屿数量

     BFS

    我们遍历每个节点,每次遇到1得节点,类似扫雷中,将这个节点周围

    得所有为1得节点全部置为0(这个步骤我们利用队列实现,不停将该节点周围

    得节点压入队列直到维护条件不成立),每次将一个区域得1置为0,最后我们可以

    计算出总共有几个搜索块,就是答案了

    时间O(m*n)(需要遍历每个节点)空间O(min(m,n))(极端情况下)

     1 class Solution {
     2     public int numIslands(char[][] grid) {
     3         int count=0;
     4         for(int i=0;i<grid.length;i++){
     5             for(int j=0;j<grid[0].length;j++){
     6                 // 遍历每个节点找出所有得
     7                 if(grid[i][j]=='1'){
     8                     bfs(grid,i,j);
     9                     count++;
    10                 }          
    11             }
    12         }
    13         return count;
    14     }
    15 
    16     private void bfs(char[][] grid,int i,int j){
    17         Queue<int[]> queue = new LinkedList<>();
    18         queue.add(new int[]{i,j});
    19         while(!queue.isEmpty()){
    20             // 取出当前节点位置,并将其相连节点压入队列
    21             int[] temp = queue.poll();
    22             i = temp[0];
    23             j = temp[1];
    24             if(0<=i && i<grid.length && 0<=j && j<grid[0].length && grid[i][j]=='1'){
    25                 grid[i][j]='0';
    26                 queue.add(new int[]{i+1,j});
    27                 queue.add(new int[]{i-1,j});
    28                 queue.add(new int[]{i,j+1});
    29                 queue.add(new int[]{i,j-1});
    30             }
    31         }
    32     }
    33 }
    争取早日不再是一只菜鸡
  • 相关阅读:
    Odoo电子数据交换(EDI)
    WMS8_仓库配置
    odoo写邮件添加收件人
    Odoo HR Payslip
    openERP邮件(发信、收信)
    Multi-company rules
    MRP Force Reservation的作用
    使用虚拟机VM运行Linux版OpenERP
    采购预付款
    消除递归的方法
  • 原文地址:https://www.cnblogs.com/jchen104/p/14812302.html
Copyright © 2011-2022 走看看