class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { if (matrix.empty()) return vector<int>(); vector<int> ret; //输入矩阵行数 int m = matrix.size() - 1; //输入矩阵的列数 int n = matrix[0].size() - 1; for (int x = 0, y = 0; x <= m && y <= n; x++, y++) { //输出矩阵首行 for(int j=y ; j<=n ; ++j) { ret.push_back(matrix[x][j]); }//while //输出矩阵最右列 for (int i = x + 1; i <= m; ++i) { ret.push_back(matrix[i][n]); }//while //输出矩阵最底行 for (int j = n - 1; j >= y && x != m; --j) { ret.push_back(matrix[m][j]); } //输出矩阵最左列 for (int i = m - 1; i > x && y != n; --i) { ret.push_back(matrix[i][y]); } m--; n--; }//for return ret; } };
补充一个使用dfs思想的python实现代码:
1 class Solution: 2 # matrix类型为二维列表,需要返回列表 3 def __init__(self): 4 self.result = [] 5 self.visited = [] 6 7 def goRight(self,matrix,i,j,row,column,direct): 8 if j + 1 < column and self.visited[i][j+1] == 0: 9 self.result.append(matrix[i][j+1]) 10 self.visited[i][j+1] = 1 11 self.dfs(matrix,i,j+1,row,column,direct) 12 13 def goDown(self,matrix,i,j,row,column,direct): 14 if i + 1 < row and self.visited[i+1][j] == 0: 15 self.result.append(matrix[i+1][j]) 16 self.visited[i+1][j] = 1 17 self.dfs(matrix,i+1,j,row,column,direct) 18 19 def goLeft(self,matrix,i,j,row,column,direct): 20 if j - 1 >= 0 and self.visited[i][j-1] == 0: 21 self.result.append(matrix[i][j-1]) 22 self.visited[i][j-1] = 1 23 self.dfs(matrix,i,j-1,row,column,direct) 24 25 def goUp(self,matrix,i,j,row,column,direct): 26 if i - 1 >= 0 and self.visited[i-1][j] == 0: 27 self.result.append(matrix[i-1][j]) 28 self.visited[i-1][j] = 1 29 self.dfs(matrix,i-1,j,row,column,direct) 30 31 def dfs(self,matrix,i,j,row,column,direct): 32 if direct == 0: 33 self.goRight(matrix,i,j,row,column,0) 34 self.goDown(matrix,i,j,row,column,1) 35 self.goLeft(matrix,i,j,row,column,2) 36 self.goUp(matrix,i,j,row,column,3) 37 if direct == 1: 38 self.goDown(matrix,i,j,row,column,1) 39 self.goLeft(matrix,i,j,row,column,2) 40 self.goUp(matrix,i,j,row,column,3) 41 self.goRight(matrix,i,j,row,column,0) 42 if direct == 2: 43 self.goLeft(matrix,i,j,row,column,2) 44 self.goUp(matrix,i,j,row,column,3) 45 self.goRight(matrix,i,j,row,column,0) 46 self.goDown(matrix,i,j,row,column,1) 47 if direct == 3: 48 self.goUp(matrix,i,j,row,column,3) 49 self.goRight(matrix,i,j,row,column,0) 50 self.goDown(matrix,i,j,row,column,1) 51 self.goLeft(matrix,i,j,row,column,2) 52 53 def spiralOrder(self, matrix): 54 row = len(matrix) 55 if row == 0: 56 return [] 57 column = len(matrix[0]) 58 self.visited = [[0 for c in range(column)] for r in range(row)] 59 self.result.append(matrix[0][0]) 60 self.visited[0][0] = 1 61 self.dfs(matrix,0,0,row,column,0) 62 return self.result 63 # write code here