solution.md 2.1 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
# 螺旋矩阵

<p>给你一个 <code>m</code> 行 <code>n</code> 列的矩阵 <code>matrix</code> ,请按照 <strong>顺时针螺旋顺序</strong> ,返回矩阵中的所有元素。</p><p> </p><p><strong>示例 1:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /><pre><strong>输入:</strong>matrix = [[1,2,3],[4,5,6],[7,8,9]]<strong><br />输出:</strong>[1,2,3,6,9,8,7,4,5]</pre><p><strong>示例 2:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /><pre><strong>输入:</strong>matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]<strong><br />输出:</strong>[1,2,3,4,8,12,11,10,9,5,6,7]</pre><p> </p><p><strong>提示:</strong></p><ul>	<li><code>m == matrix.length</code></li>	<li><code>n == matrix[i].length</code></li>	<li><code>1 <= m, n <= 10</code></li>	<li><code>-100 <= matrix[i][j] <= 100</code></li></ul>

## template

```java
class Solution {
	public List<Integer> spiralOrder(int[][] matrix) {
		List<Integer> res = new ArrayList<Integer>();
		if (matrix.length == 0 || (matrix.length == 1 && matrix[0].length == 0))
			return res;
		int left = 0;
		int right = matrix[0].length - 1;
		int top = 0;
		int bottom = matrix.length - 1;
		int num = (right + 1) * (bottom + 1);
		while (num > 0) {
			for (int j = left; j <= right; j++) {
				res.add(matrix[top][j]);
				num--;
			}
			if (num <= 0)
				break;
			top++;
			for (int i = top; i <= bottom; i++) {
				res.add(matrix[i][right]);
				num--;
			}
			if (num <= 0)
				break;
			right--;
			for (int j = right; j >= left; j--) {
				res.add(matrix[bottom][j]);
				num--;
			}
			if (num <= 0)
				break;
			bottom--;
			for (int i = bottom; i >= top; i--) {
				res.add(matrix[i][left]);
				num--;
			}
			if (num <= 0)
				break;
			left++;
		}
		return res;
	}
}
```

## 答案

```java

```

## 选项

### A

```java

```

### B

```java

```

### C

```java

```