LeetCode(剑指 Offer)- 29. 顺时针打印矩阵
Posted 放羊的牧码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(剑指 Offer)- 29. 顺时针打印矩阵相关的知识,希望对你有一定的参考价值。
题目链接:点击打开链接
题目大意:略。
解题思路:略。
相关企业
- 哔哩哔哩
- 字节跳动
- 苹果(Apple)
- 微软(Microsoft)
- 谷歌(Google)
- 彭博(bloomberg)
- 亚马逊(Amazon)
- 甲骨文(Oracle)
- VMware
- 兴业银行
AC 代码
- Java
// 解决方案(1)
class Solution
public int[] spiralOrder(int[][] matrix)
if(matrix.length == 0) return new int[0];
int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1, x = 0;
int[] res = new int[(r + 1) * (b + 1)];
while(true)
for(int i = l; i <= r; i++) res[x++] = matrix[t][i]; // left to right
if(++t > b) break;
for(int i = t; i <= b; i++) res[x++] = matrix[i][r]; // top to bottom
if(l > --r) break;
for(int i = r; i >= l; i--) res[x++] = matrix[b][i]; // right to left
if(t > --b) break;
for(int i = b; i >= t; i--) res[x++] = matrix[i][l]; // bottom to top
if(++l > r) break;
return res;
// 解决方案(2)
class Solution
public int[] spiralOrder(int[][] matrix)
if (matrix.length == 0) return new int[0];
int m = matrix.length, n = matrix[0].length;
final int[] direct = 6, 2, 4, 8;
int[][] block = new int[m][n];
int[] res = new int[m * n];
int i = 0, j = 0, q = 0, p = 0, dir;
while (true)
dir = direct[p];
if (dir == 6) // RIGHT
if (j >= n || block[i][j] == 1)
p = (p + 1) % 4;
j--;
i++;
continue;
block[i][j] = 1;
res[q++] = matrix[i][j++];
else if (dir == 2) // DOWN
if (i >= m || block[i][j] == 1)
p = (p + 1) % 4;
i--;
j--;
continue;
block[i][j] = 1;
res[q++] = matrix[i++][j];
else if (dir == 4) // LEFT
if (j < 0 || block[i][j] == 1)
p = (p + 1) % 4;
j++;
i--;
continue;
block[i][j] = 1;
res[q++] = matrix[i][j--];
else // UP
if (i < 0 || block[i][j] == 1)
p = (p + 1) % 4;
i++;
j++;
continue;
block[i][j] = 1;
res[q++] = matrix[i--][j];
if (q == m * n)
break;
return res;
- C++
class Solution
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
if (matrix.empty()) return ;
int l = 0, r = matrix[0].size() - 1, t = 0, b = matrix.size() - 1;
vector<int> res;
while(true)
for (int i = l; i <= r; i++) res.push_back(matrix[t][i]); // left to right
if (++t > b) break;
for (int i = t; i <= b; i++) res.push_back(matrix[i][r]); // top to bottom
if (l > --r) break;
for (int i = r; i >= l; i--) res.push_back(matrix[b][i]); // right to left
if (t > --b) break;
for (int i = b; i >= t; i--) res.push_back(matrix[i][l]); // bottom to top
if (++l > r) break;
return res;
;
以上是关于LeetCode(剑指 Offer)- 29. 顺时针打印矩阵的主要内容,如果未能解决你的问题,请参考以下文章