• 矩阵中广度优先搜索的使用


    题目信息

    这道题是leetCode中的542题-01矩阵,
    题目大意是给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。两个相邻元素间的距离为 1 
    输入
        [0 0 0]
        [0 1 0]
        [0 0 0]
    输出
        [0 0 0]
        [0 1 0]
        [0 0 0]
    
    输入
        [0 0 0]
        [0 1 0]
        [1 1 1]
    输出
        [0 0 0]
        [0 1 0]
        [1 2 1]
    注意:
        给定矩阵的元素个数不超过 10000。
        给定矩阵中至少有一个元素是 0。
        矩阵中的元素只在四个方向上相邻: 上、下、左、右

    解题思路

    这道题是典型的可以使用BFS去解决的,首页遍历数组将所有非0的赋值为-1,遍历的同时将为0的坐标保存到数组中。遍历之前保存0的数组的上下左右,在当前为0坐标的数据上加1,并且保存到数组中

    代码

    class matrixSolution {
        func matrix(_ matrix: [[Int]]) -> [[Int]] {
            var tempMatrix = matrix;
            var stack: [[Int]] = [];
            let rowNumber = matrix.count;
            let lineNumber = matrix[0].count;
            
            // 遍历备份的数组,将所有不为0的赋值为-1,将为0的坐标保存到另外一个数组
            for (i, list) in matrix.enumerated() {
                for (j, item) in list.enumerated() {
                    if (item == 0) {
                        stack.append([i, j]);
                    } else {
                        tempMatrix[i][j] = -1;
                    }
                }
            }
            
            // 这两个数组用于取值上下左右遍历
            let bx = [-1, 1, 0, 0];
            let by = [0, 0, -1, 1];
            
            // 遍历stack队列 知道为空时为止
            while !stack.isEmpty {
                let point = stack.first;
                stack.removeFirst();
                let x = point![0];
                let y = point![1];
                
                // 向周围四个方向遍历
                for ibx in 0..<4 {
                    let newX = x + bx[ibx];
                    let newY = y + by[ibx];
                    if newX >= 0 && newX < rowNumber && newY >= 0 && newY < lineNumber && tempMatrix[newX][newY] == -1 {
                        tempMatrix[newX][newY] = tempMatrix[x][y] + 1;
                        stack.append([newX, newY]);
                    }
                }
                
            }
            return tempMatrix;
        }
    }

    题目链接


  • 相关阅读:
    Linux命令笔记
    拆功放板笔记
    从输入 URL 到页面加载完的过程中都发生了什么---优化
    python学习笔记(三)
    python学习笔记(二)
    python学习笔记(一)
    公交wifi运营平台分析
    testNG小试牛刀
    maven小项目注册服务(三)--web模块
    用maven进行测试
  • 原文地址:https://www.cnblogs.com/muzichenyu/p/12720173.html
Copyright © 2020-2023  润新知