Question
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n2
in spiral order.
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n2
in spiral order.
Given a square matrix mat
, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
1329. Sort the Matrix Diagonally
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix’s end. For example, the matrix diagonal starting from
mat[2][0]
, wheremat
is a6 x 3
matrix, includes cellsmat[2][0]
,mat[3][1]
, andmat[4][2]
.Given an
m x n
matrixmat
of integers, sort each matrix diagonal in ascending order and return the resulting matrix.
分别遍历数组的两条边。
按对角线顺序进行遍历,用列表记录访问过的数字。
排序列表后按对角线填入原数组。
1 | class Solution { |
2319. Check if Matrix Is X-Matrix
A square matrix is said to be an X-Matrix if both of the following conditions hold:
- All the elements in the diagonals of the matrix are non-zero.
- All other elements are 0.
Given a 2D integer array
grid
of sizen x n
representing a square matrix, returntrue
* ifgrid
is an X-Matrix*. Otherwise, returnfalse
.
遍历,直接判断是否在对角线上,如果在且位置为0,则返回false。
如果不在对角线上,且位置部位0,则返回false。
1 | class Solution { |
304. Range Sum Query 2D - Immutable
Given a 2D matrix
matrix
, handle multiple queries of the following type:
- Calculate the sum of the elements of
matrix
inside the rectangle defined by its upper left corner(row1, col1)
and lower right corner(row2, col2)
.Implement the NumMatrix class:
NumMatrix(int[][] matrix)
Initializes the object with the integer matrixmatrix
.int sumRegion(int row1, int col1, int row2, int col2)
Returns the sum of the elements ofmatrix
inside the rectangle defined by its upper left corner(row1, col1)
and lower right corner(row2, col2)
.
前缀和/动态规划,用一个dp[][]数组记录到matrix[0][0]到matrix[i][j]区域的和。
计算两个点之间形成的总数只需用外侧的位置的前缀和加上内侧位置的前缀和,然后减去两者交换长宽位置的前缀和即可。
计算dp[][]数组时,需要将其上侧与左侧所有数字加和,并加上matrix[][]上该位置对应的元素。
用dp[i][j-1] - dp[i-1][j-1]计算出左侧所有数字之和,dp[i-1][j]则是上侧所有数字之和。
1 | class NumMatrix { |
暴力搜索,直接计算从row1, col1到row2, col2的元素加和。
1 | class NumMatrix { |
Given a 2D integer array
matrix
, return the transpose ofmatrix
.The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix’s row and column indices.
记录一个新数组res[][]。
双重循环,交换下标将matrix[i][j]复制到res[j][i],最后返回。
1 | class Solution { |
1091. Shortest Path in Binary Matrix
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:
All the visited cells of the path are 0.
All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
The length of a clear path is the number of visited cells of this path.
由于不能重复搜索,且需要在搜索时将搜索过的位置改变,因此需要采用BFS逐一层级的搜索。
逐层级搜索并记录层级。最后返回层级+1即可。
(还有更快的优化算法A*)
整体没有改变太多,基本还是方法二那种。启发式函数改为切比雪夫距离距离。
距离计算方法有很多,常用启发式函数有这几种。选择合适的启发式函数有利于速度的提升。这题可以用好几种启发式函数,初学都可以试着都写一下。
曼哈顿距离(Manhattan Distance)
一般只能在四个方向上移动时用(右、左、上、下)
对角线距离(Diagonal Distance):
当我们只允许向八个方向移动时用(国际象棋中的王移动方式那种)
欧几里得距离(Euclidean Distance):
不受限制,允许向任何方向移动时。
切比雪夫距离(Chebyshev Distance):
可参考:[https://leetcode-cn.com/problems/minimum-time-visiting-all-points/solution/fang-wen-suo-you-dian-de-zui-xiao-shi-jian-by-le-2/](LeetCode 1266)
1 | class Solution { |
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
Return the total number of provinces.
DFS搜索,当map[i][i] = 1时加入搜索。
搜索时将map[i][i]设为0。遍历并递归其数列。
当map[i][i]等于0时,返回。
1 | class Solution { |
Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
遍历所有点,如果等于1则对其进行DFS搜索。
在搜索的同时将1设为0。
如果等于0则递归返回。
1 | class Solution { |
同样是dfs搜索遍历每个位置,然而这个方法使用visited[][]数组来记录点是否被访问过。
1 | class Solution { |
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
将起始点设置为第一行的最后一列。
如果搜寻目标大于该点则向下搜索。
如果搜寻目标小于该点则向左搜索。
1 | class Solution { |
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
此方法是in-place算法。
visited[][]数组记录访问情况,遍历所有位置,如果已访问则跳过。
循环替换矩阵上的每一个位置,如果已经访问过则break。
如果未访问则将要替换位置的值保存,并且在visited[][]数组上记录。
然后继续遍历替换过的位置。
1 | class Solution { |
此方法类似Solution 1,但是并非原地算法。
1 | class Solution { |
辅助方法getPixel计算旋转后的像素位置。
旋转时候矩阵内的四个分区的像素会互相替换。
因此需要将需要旋转的初始位置记录进入队列。
旋转图像时根据getPixel方法计算出需要替换的位置。
然后依次替换像素。
1 | class Solution { |
问题
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
循环,创建一个上界和一个下界。
当达到界限时,改变方向。
更新上界和下界的数值。
当上界小于下界时返回。
1 | class Solution { |
问题
According to Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
- Any live cell with fewer than two live neighbors dies as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population.
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.
辅助方法,计算每个位置四周有生命的总和。
根据规则填写到新数组。
1 | class Solution { |
问题
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.In one shift operation:
Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.
遍历整个数组,将索引值加上移动的次数,得到新的位置。
1 | class Solution { |