[LeetCode] 01 Matrix 零一矩阵】的更多相关文章

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. Example 1: Input: 0 0 0 0 1 0 0 0 0 Output: 0 0 0 0 1 0 0 0 0 Example 2: Input: 0 0 0 0 1 0 1 1 1 Output: 0 0 0 0 1 0…
问题: https://leetcode.com/problems/01-matrix/#/description 基本思路:广度优先遍历,根据所有最短距离为N的格找到所有距离为N+1的格,直到所有的格都找到了最短距离. 具体步骤: 首先初始化矩阵,值为0的格其最短距离也是0,保持不变:值为1的格是后面需要计算最短距离的格,我们需要一个整数来标识它们,这里可以选择一个负数或者整数的最大值. 然后进行若干轮计算,第N轮会根据已经计算出的最短距离为N-1的所有格,来找出所有最短距离为N的格. 例如,…
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 此题跟之前那道Spiral Matrix 螺旋矩阵 本质上没什么区别,就相当于个类似逆运算的过…
Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order. For example,Given n =3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题意:给定整数n,以螺旋的方式形成一个n×n个矩阵. 思路:这题的思路和spiral matr…
题意 # 思路 我一开始的时候想的是嘴 # 实现 ```cpp // // include "../PreLoad.h" class Solution { public: /** * 三重循环,最外层为所有1的结点,里面两层是实现BFS * 导致时间复杂度过高,待优化 * @param matrix * @return */ vector< vector<int>> layouts = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; ve…
给定一个矩阵,把零值所在的行和列都置为零.例如: 1 2 3 1 3 1 1 1 操作之后变为 1 3 0 0 0 1 1 方法1: 赋值另存一个m*n的矩阵,在原矩阵为零的值相应置新的矩阵行和列为零.额外空间为O(m*n). 方法2: 两个数组,bool[m] 和 bool[n] 分别存某行有零,后者某列有零.之后根据数组值将原矩阵相应位置置零.额外空间O(m + n). class Solution { public: void setZeroes(vector<vector<int>…
01 Matrix 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/01-matrix/description/ Description Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. Example 1: Input: 0 0 0 0…
Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal. Example: Input: [[0,1,1,0], [0,1,1,0], [0,0,0,1]] Output: 3 Hint: The number of elements in the given matr…
给予一个矩阵,矩阵有1有0,计算每一个1到0需要走几步,只能走上下左右. 解法一: 利用dp,从左上角遍历一遍,再从右下角遍历一遍,dp存储当前位置到0的最短距离. 十分粗心的搞错了col和row,改了半天………… Runtime: 132 ms, faster than 98.88% of C++ online submissions for 01 Matrix. class Solution { public: vector<vector<int>> updateMatrix(…
542. 01 Matrix https://www.cnblogs.com/grandyang/p/6602288.html 将所有的1置为INT_MAX,然后用所有的0去更新原本位置为1的值. 最短距离肯定使用bfs. 每次更新了值的地方还要再加入队列中 . class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { ].size…