本文主要是介绍java常用算法之螺旋矩阵,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
给定一个m*n矩阵,返回所有元素在矩阵中的螺旋序列,例如:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
返回[1,2,3,6,9,8,7,4,5].
算法实现如下:
public static List<Integer> spiralMatrix(int source[][]) {List<Integer> result = new ArrayList();int columns = source[0].length;int rows = source.length;int m = 0;int length = rows * columns;while (result.size() < length) {for (int i = m; i < columns; i++) {result.add(source[m][i]);}if (result.size() == length) {break;}for (int i = m + 1; i < rows; i++) {result.add(source[i][columns - 1]);}if (result.size() == length) {break;}for (int i = columns - 2; i > (m - 1); i--) {result.add(source[rows - 1][i]);}if (result.size() == length) {break;}for (int i = rows - 2; i > m; i--) {result.add(source[i][m]);}m++;columns = columns - 1;rows = rows - 1;}return result;}public static void main(String[] args) {int a[][] = { { 1, 3, 5, 6 }, { 10, 7, 8, 2 }, { 9, 12, 11, 13 },{ 17, 19, 21, 22 }, { 31, 32, 35, 37 } };List<Integer> result = spiralMatrix(a);System.err.println(result.toString());}
输出结果:
[1, 3, 5, 6, 2, 13, 22, 37, 35, 32, 31, 17, 9, 10, 7, 8, 11, 21, 19, 12]
这篇关于java常用算法之螺旋矩阵的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!