本文主要是介绍LeetCode 54 Spiral Matrix (模拟 蛇形填数),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
题目链接:https://leetcode.com/problems/spiral-matrix/
题目分析:模拟填数过程即可
public class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> ans = new ArrayList<>();int n = matrix.length;if (n == 0) {return ans;}int m = matrix[0].length;int all = n * m, cnt = 0, i = 0, j = 0;boolean[][] vis = new boolean[n + 1][m + 1];while (cnt < all) {while (j < m && !vis[i][j]) {vis[i][j] = true;cnt ++;ans.add(matrix[i][j ++]);}j --;i ++;while (i < n && !vis[i][j]) {vis[i][j] = true;cnt ++;ans.add(matrix[i ++][j]);}i --;j --;while (j >= 0 && !vis[i][j]) {vis[i][j] = true;cnt ++;ans.add(matrix[i][j --]);}j ++;i --;while (i >= 0 && !vis[i][j]) {vis[i][j] = true;cnt ++;ans.add(matrix[i --][j]);}i ++;j ++;}return ans;}
}
其实不开boolean数组也可以
public class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> ans = new ArrayList<>();int n = matrix.length;if (n == 0) {return ans;}int m = matrix[0].length;int left = 0, right = m - 1, down = n - 1, up = 0;while (true) {for (int j = left; j <= right; j ++) {ans.add(matrix[up][j]);}up ++;if (left > right || up > down) {break;}for (int i = up; i <= down; i ++) {ans.add(matrix[i][right]);}right --;if (left > right || up > down) {break;}for (int j = right; j >= left; j --) {ans.add(matrix[down][j]);}down --;if (left > right || up > down) {break;}for (int i = down; i >= up; i --) {ans.add(matrix[i][left]);}left ++;if (left > right || up > down) {break;}}return ans;}
}
这篇关于LeetCode 54 Spiral Matrix (模拟 蛇形填数)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!