NC38:螺旋矩阵
螺旋矩阵
http://www.nowcoder.com/questionTerminal/7edf70f2d29c4b599693dc3aaeea1d31
给定一个整型矩阵matrix,请按照转圈的方式打印它。
例如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 打印结果为: 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11, 10
思路:printEdge打印矩阵的外层,层层打印
打印过程:1 2 3---4 8 12---16 15 14--13 9 5---6 ---7---11---10
import java.util.*; public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> list=new ArrayList<>(); if(matrix==null || matrix.length==0 || matrix[0].length==0){ return list; } int StartLeft=0; int StartRight=0; int EndLeft=matrix.length-1; int EndRight=matrix[0].length-1; while(StartLeft<=EndLeft && StartRight<=EndRight){ add(matrix,list,StartLeft++,StartRight++,EndLeft--,EndRight--); } return list; } public void add(int[][] matrix,ArrayList<Integer> list,int StartLeft, int StartRight,int EndLeft,int EndRight){ if(StartLeft==EndLeft){ for(int i=EndLeft;i<=EndRight;i++){ list.add(matrix[StartLeft][i]); } } else if(StartRight==EndRight){ for(int i=StartLeft;i<=EndLeft;i++){ list.add(matrix[i][StartRight]); } } else{ int curL=StartLeft; int curR=StartRight; while(curR!=EndRight){ list.add(matrix[StartLeft][curR]); curR++; } while(curL!=EndLeft){ list.add(matrix[curL][EndRight]); curL++; } while(curR!=StartRight){ list.add(matrix[EndLeft][curR]); curR--; } while(curL!=StartLeft){ list.add(matrix[curL][StartRight]); curL--; } } } }
放到一个函数里:
import java.util.ArrayList; public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> resultList = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return resultList; } if (matrix.length == 1 && matrix[0].length == 1) { resultList.add(matrix[0][0]); return resultList; } int starti = 0; int startj = 0; int endi = matrix.length - 1; int endj = matrix[0].length - 1; while (starti <= endi&& startj <= endj) { //当只有一行一列的情况 if (starti == endi) { for (int j = startj; j <= endj; j++) { resultList.add(matrix[starti][j]); } return resultList; } else if (startj == endj) { for (int i = starti; i <= endi; i++) { resultList.add(matrix[i][startj]); } return resultList; } else { int i = starti; int j = startj; //上边 while (j < endj) { resultList.add(matrix[i][j++]); } //右边 while (i < endi) { resultList.add(matrix[i++][j]); } //下边 while (j > startj) { resultList.add(matrix[i][j--]); } //上边,加一的目的是不需要重复的加,只需要等待下一次循环就好 while (i > starti) { resultList.add(matrix[i--][j]); } starti++; startj++; endi--; endj--; } } return resultList; } }
名企高频面试算法题解 文章被收录于专栏
牛客题霸 - 程序员面试高频题 - 题解