class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty())
return vector<int>(); vector<int> ret; //输入矩阵行数
int m = matrix.size() - ; //输入矩阵的列数
int n = matrix[].size() - ; for (int x = , y = ; x <= m && y <= n; x++, y++)
{
//输出矩阵首行
for(int j=y ; j<=n ; ++j)
{
ret.push_back(matrix[x][j]);
}//while //输出矩阵最右列
for (int i = x + ; i <= m; ++i)
{
ret.push_back(matrix[i][n]);
}//while //输出矩阵最底行
for (int j = n - ; j >= y && x != m; --j)
{
ret.push_back(matrix[m][j]);
} //输出矩阵最左列
for (int i = m - ; i > x && y != n; --i)
{
ret.push_back(matrix[i][y]);
} m--;
n--;
}//for return ret;
}
};

补充一个使用dfs思想的python实现代码:

 class Solution:
# matrix类型为二维列表,需要返回列表
def __init__(self):
self.result = []
self.visited = [] def goRight(self,matrix,i,j,row,column,direct):
if j + < column and self.visited[i][j+] == :
self.result.append(matrix[i][j+])
self.visited[i][j+] =
self.dfs(matrix,i,j+,row,column,direct) def goDown(self,matrix,i,j,row,column,direct):
if i + < row and self.visited[i+][j] == :
self.result.append(matrix[i+][j])
self.visited[i+][j] =
self.dfs(matrix,i+,j,row,column,direct) def goLeft(self,matrix,i,j,row,column,direct):
if j - >= and self.visited[i][j-] == :
self.result.append(matrix[i][j-])
self.visited[i][j-] =
self.dfs(matrix,i,j-,row,column,direct) def goUp(self,matrix,i,j,row,column,direct):
if i - >= and self.visited[i-][j] == :
self.result.append(matrix[i-][j])
self.visited[i-][j] =
self.dfs(matrix,i-,j,row,column,direct) def dfs(self,matrix,i,j,row,column,direct):
if direct == :
self.goRight(matrix,i,j,row,column,)
self.goDown(matrix,i,j,row,column,)
self.goLeft(matrix,i,j,row,column,)
self.goUp(matrix,i,j,row,column,)
if direct == :
self.goDown(matrix,i,j,row,column,)
self.goLeft(matrix,i,j,row,column,)
self.goUp(matrix,i,j,row,column,)
self.goRight(matrix,i,j,row,column,)
if direct == :
self.goLeft(matrix,i,j,row,column,)
self.goUp(matrix,i,j,row,column,)
self.goRight(matrix,i,j,row,column,)
self.goDown(matrix,i,j,row,column,)
if direct == :
self.goUp(matrix,i,j,row,column,)
self.goRight(matrix,i,j,row,column,)
self.goDown(matrix,i,j,row,column,)
self.goLeft(matrix,i,j,row,column,) def spiralOrder(self, matrix):
row = len(matrix)
if row == :
return []
column = len(matrix[])
self.visited = [[ for c in range(column)] for r in range(row)]
self.result.append(matrix[][])
self.visited[][] =
self.dfs(matrix,,,row,column,)
return self.result
# write code here
05-12 14:11