题目链接:点击打开链接
题目大意:略。
解题思路:略。
相关企业
哔哩哔哩
字节跳动
苹果(Apple)
微软(Microsoft)
谷歌(Google)
彭博(bloomberg)
亚马逊(Amazon)
甲骨文(Oracle)
VMware
兴业银行
AC 代码
Java
// 解决方案(1) class Solution { public List<Integer> spiralOrder(int[][] matrix) { int m = matrix.length, n = matrix[0].length; final int[] direct = {6, 2, 4, 8}; int[][] block = new int[m][n]; List<Integer> list = new ArrayList<>(); int i = 0, j = 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; list.add(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; list.add(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; list.add(matrix[i][j--]); } else { // UP if (i < 0 || block[i][j] == 1) { p = (p + 1) % 4; i++; j++; continue; } block[i][j] = 1; list.add(matrix[i--][j]); } if (list.size() == m * n) { break; } } return list; } } // 解决方案(2) class Solution { public List<Integer> spiralOrder(int[][] matrix) { if(matrix.length == 0) return new ArrayList<>(); int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1; List<Integer> list = new ArrayList<>(); while(true) { for(int i = l; i <= r; i++) list.add(matrix[t][i]); // left to right if(++t > b) break; for(int i = t; i <= b; i++) list.add(matrix[i][r]); // top to bottom if(l > --r) break; for(int i = r; i >= l; i--) list.add(matrix[b][i]); // right to left if(t > --b) break; for(int i = b; i >= t; i--) list.add(matrix[i][l]); // bottom to top if(++l > r) break; } return list; } }
- 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; } };