螺旋矩阵1 力扣54题
没有复杂的数据结构,按照流程复现处理好边界问题即可。
第一种解法:设置边界,不断更新边界条件。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector <int> ans;
if(matrix.empty()) return ans; //若数组为空,直接返回答案
int u = 0; //赋值上下左右边界
int d = matrix.size() - 1;
int l = 0;
int r = matrix[0].size() - 1;
while(true){
for(int i=l;i<=r;++i) ans.push_back(matrix[u][i]);
if(++u>d) break;
for(int i=u;i<=d;++i) ans.push_back(matrix[i][r]);
if(--r<l) break;
for(int i=r;i>=l;--i) ans.push_back(matrix[d][i]);
if(--d<u) break;
for(int i=d;i>=u;--i) ans.push_back(matrix[i][l]);
if(++l>r) break;
}
return ans;
}
};
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
ans = []
left,top=0,0
right=len(matrix[0])
bottom=len(matrix)
while(True):
for i in range(top,right):
ans.append(matrix[top][i])
top += 1 #重新定义上边界
if(top>=bottom):
break
for j in range(top,bottom):
ans.append(matrix[j][right-1])
right = right - 1 #重新定义右边界
if(right<=left):
break
for m in range(right-1,left-1,-1):
ans.append(matrix[bottom-1][m])
bottom = bottom - 1 #重新定义下边界
if(bottom<=top):
break
for n in range(bottom-1,top-1,-1):
ans.append(matrix[n][left])
left = left + 1 #重新定义左边界
if(left>=right):
break
return ans
第二种解法不预先设置边界,需要一个数组记录元素是否被访问 dx dy为方向矩阵 移动的四个方向 从左到右 上到下 右到左 下到上
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector <int> ans;
int m = matrix.size();
int n = matrix[0].size();
if(matrix.empty()) return ans; //若数组为空,直接返回答案
vector<vector<bool>> st(m,vector<bool>(n,false));
int x = 0,y=0,d=0;
int dx[] = {0,1,0,-1},dy[]={1,0,-1,0};
for(int i=0;i<m*n;i++){
ans.push_back(matrix[x][y]);
int a = x + dx[d];
int b = y + dy[d];
st[x][y] = true;
if(a<0||a>=m||b<0||b>=n||st[a][b]){
d = (d+1) % 4;
}
x += dx[d];
y += dy[d];
}
return ans;
}
};
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
ans = []
m = len(matrix)
n = len(matrix[0])
import numpy as np
# st = [[0 for i in range(m+2)] for j in range(n+2)]
st = np.zeros((m,n),dtype=int)
x=0
y=0
d=0
dx = [0,1,0,-1]
dy = [1,0,-1,0]
for i in range(m*n):
ans.append(matrix[x][y])
st[x][y]=1
a=x+dx[d]
b=y+dy[d]
if(a<0 or a>=m or b<0 or b>=n or st[a][b]):
d = (d+1)%4
x +=dx[d]
y += dy[d]
return ans
螺旋矩阵2 力扣59
题解:1的逆过程,解法与1相同。第一种提前设置好边界
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int top=0;
int left = 0;
int right = n-1;
int bottom = n-1;
int a = 1;
while (true) {
for (int i = left; i <= right; i++) {
matrix[top][i] = a;
a += 1;
}
if (++top > bottom) break;
for (int i = top; i <= bottom; i++) {
matrix[i][right] = a;
a += 1;
}
if (--right < left) break;
for (int i = right; i >= left; i--) {
matrix[bottom][i] = a;
a += 1;
}
if (--bottom < top) break;
for (int i = bottom; i >= top; i--) {
matrix[i][left] = a;
a += 1;
}
if (++left > right) break;
}
return matrix;
}
};
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [ [0 for i in range(n)] for j in range(n)]
top=left=0
bottom=right=n-1
a = 1
while(True):
for i in range(top,right+1):
matrix[top][i] = a
a +=1
top +=1
if(top>bottom):
break
for i in range(top,bottom+1):
matrix[i][right] = a
a += 1
right -= 1
if(right<left):
break
for i in range(right,left-1,-1):
matrix[bottom][i] = a
a += 1
bottom -= 1
if(bottom<top):
break
for i in range(bottom,top-1,-1):
matrix[i][left] = a
a += 1
left += 1
if(left>right):
break
return matrix
第二种
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n,0));
int x=0,y=0,d=0;
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
for(int i=1;i<=n*n;i++){
matrix[x][y] = i;
int a = x + dx[d];
int b = y + dy[d];
if(a<0||a>=n||b>=n||b<0||matrix[a][b]!=0){
d = (d+1) %4;
}
x += dx[d];
y += dy[d];
}
return matrix;
}
};
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [ [0 for i in range(n)] for j in range(n)]
x=0
y=0
d=0
dx = [0,1,0,-1]
dy = [1,0,-1,0]
len = (n * n) + 1
for i in range(1,len):
matrix[x][y]=i
a = x + dx[d]
b = y + dy[d]
if((a<0) or (a>=n) or (b<0) or (b>=n) or (matrix[a][b]!=0)):
d = (d+1) % 4
x += dx[d]
y += dy[d]
return matrix
螺旋矩阵3 力扣885
题解:与前面一样设置变换矩阵dx dy 通过观察可以发现 步长为1 1 2 2 3 3 4 4 .。不用考虑边界问题
class Solution {
public:
vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
vector<vector<int>> matrix;
int maxa = rows>cols?rows:cols;
int x= rStart;
int y=cStart;
int sum = rows* cols;
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
int d = 0;
int count =1;
while(sum){
int len = count;
for(int a =0;a<2;a++){
for(int c=1;c<=count;c++){
if(x>=0 && x<rows && y>=0 && y<cols){
matrix.push_back({x,y});
sum--;
}
x += dx[d];
y += dy[d];
}
d = (d+1) % 4;
}
count++;
}
return matrix;
}
};
螺旋矩阵4 力扣2326
和1,2,解法一样。初始化数组全为-1即可;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> matrix(m,vector<int>(n,-1)); //返回的矩阵
int x=0;
int y=0;
int d=0; //定义当前xy位置d表示运动方向
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0}; //定义运动方向数组
while(head!=nullptr){
matrix[x][y] = head->val;
int a= x+dx[d];
int b = y+dy[d];
if(a<0||a>=m||b<0||b>=n ||matrix[a][b]!=-1){
d = (d+1)%4;
}
x += dx[d];
y += dy[d];
head=head->next;
}
return matrix;
}
};
//第二种方法在需要在每次移动之前判断当前指针是否为空指针。
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> matrix(m,vector<int>(n,-1)); //返回的矩阵
int top=0;
int left=0;
int right=n-1;
int bottom=m-1;
while(head!=nullptr){
for(int i=left;i<=right;i++){
if(head==nullptr) break;
matrix[top][i]=head->val;
head=head->next;
}
if(++top>bottom || head==nullptr) break;
for(int i=top;i<=bottom;i++){
if(head==nullptr) break;
matrix[i][right]=head->val;
head=head->next;
}
if(--right<left || head==nullptr) break;
for(int i=right;i>=left;i--){
if(head==nullptr) break;
matrix[bottom][i]=head->val;
head=head->next;
}
if(--bottom<top || head==nullptr) break;
for(int i=bottom;i>=top;i--){
if(head==nullptr) break;
matrix[i][left]=head->val;
head=head->next;
}
if(++left>right || head==nullptr) break;
}
return matrix;
}
};
python 版本代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
matrix = [[-1 for i in range(n)] for j in range(m)]
x=0
y=0
d=0
dx = [0,1,0,-1]
dy = [1,0,-1,0]
while(head):
matrix[x][y]=head.val
head = head.next
a = x + dx[d]
b = y + dy[d]
if(a<0 or a>=m or b<0 or b>=n or matrix[a][b]!=-1):
d = (d+1)%4
x += dx[d]
y += dy[d]
return matrix
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
matrix = [[-1 for i in range(n)] for j in range(m)]
top=0
left=0
right=n
bottom=m
while(True):
for i in range(left,right):
if(head is not None):
matrix[top][i] = head.val
head = head.next
top +=1
if(top>=bottom or head is None):
break
for i in range(top,bottom):
if(head is not None):
matrix[i][right-1] = head.val
head = head.next
right -=1
if(left>=right or head is None):
break
for i in range(right-1,left-1,-1):
if(head is not None):
matrix[bottom-1][i] = head.val
head = head.next
bottom -=1
if(top>=bottom or head is None):
break
for i in range(bottom-1,top-1,-1):
if(head is not None):
matrix[i][left] = head.val
head = head.next
left +=1
if(left>=right or head is None):
break;
return matrix