首页 > 代码库 > Leetcode-Spiral Matrix
Leetcode-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]
.
Solution:
1 public class Solution { 2 public List<Integer> spiralOrder(int[][] matrix) { 3 List<Integer> res = new ArrayList<Integer>(); 4 int xLen = matrix.length; 5 if (xLen==0) return res; 6 int yLen = matrix[0].length; 7 if (yLen==0) return res; 8 9 int[] x = new int[]{0,1,0,-1};10 int[] y = new int[]{1,0,-1,0};11 boolean[][] printed = new boolean[xLen][yLen];12 for (int i=0;i<xLen;i++)13 Arrays.fill(printed[i],false);14 int direction = 0;15 int curX = 0, curY=0; 16 for (int i=0;i<xLen*yLen;i++){17 res.add(matrix[curX][curY]);18 printed[curX][curY] = true;19 int nextX = curX+x[direction];20 int nextY = curY+y[direction]; 21 //Determin the availability of next point.22 if (nextX>=xLen || nextX<0 || nextY>=yLen || nextY<0 || printed[nextX][nextY]){23 direction = (direction+1)%4;24 nextX = curX+x[direction];25 nextY = curY+y[direction];26 }27 curX = nextX;28 curY = nextY;29 }30 return res; 31 }32 }
Solution 2:
We actually does not need the matrix to record the visited element, because each time the direction is changed, one row or one col becomes unavailable. We only need to record and update the start and end of the available rows and clos.
1 public class Solution { 2 public List<Integer> spiralOrder(int[][] matrix) { 3 List<Integer> res = new ArrayList<Integer>(); 4 int xLen = matrix.length; 5 if (xLen==0) return res; 6 int yLen = matrix[0].length; 7 if (yLen==0) return res; 8 9 int[] x = new int[]{0,1,0,-1};10 int[] y = new int[]{1,0,-1,0}; 11 int direction = 0;12 int curX = 0, curY=0; 13 int rowStart = 0, rowEnd = xLen-1, colStart=0, colEnd=yLen-1;14 15 for (int i=0;i<xLen*yLen;i++){16 res.add(matrix[curX][curY]);17 int nextX = curX+x[direction];18 int nextY = curY+y[direction]; 19 //Determin the availability of next point.20 if (nextX>rowEnd || nextX<rowStart || nextY>colEnd || nextY<colStart){21 direction = (direction+1)%4;22 nextX = curX+x[direction];23 nextY = curY+y[direction];24 //Update the availability of rows and cols according the direction change.25 if (direction==1) rowStart++;26 if (direction==2) colEnd--;27 if (direction==3) rowEnd--;28 if (direction==0) colStart++;29 }30 curX = nextX;31 curY = nextY;32 }33 return res; 34 }35 }
Leetcode-Spiral Matrix
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。