题解 | #螺旋矩阵#

螺旋矩阵

http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

package NCexercise.E40;

import org.junit.Test;

import java.util.ArrayList;

public class NC38 {
@Test
public void test() {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
ArrayList<integer> list = spiralOrder(matrix);
System.out.println(list);
}</integer>

public ArrayList<Integer> spiralOrder(int[][] matrix) {
    ArrayList<Integer> res = new ArrayList<>();
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return res;
    }
    int m = matrix.length;//m行
    int n = matrix[0].length;//n列

    int left = 0;
    int right = n - 1;
    int top = 0;
    int bottom = m - 1;

    //边界条件:right == n/2  left == n/2-1
    //        bottom == n/2 top == n/2-1
    int temp = 0;
    while (right >= n / 2 && left <= n / 2 && bottom >= m / 2 && top <= m / 2) {
        //向右走
        for (int i = left; i <= right; i++) {
            temp = matrix[top][i];
            res.add(temp);
        }
        top++;
        if (top > bottom) {
            break;
        }
        //向下走
        for (int i = top; i <= bottom; i++) {
            temp = matrix[i][right];
            res.add(temp);
        }
        right--;
        if (right < left) {
            break;
        }
        //向左走
        for (int i = right; i >= left; i--) {
            temp = matrix[bottom][i];
            res.add(temp);
        }
        bottom--;
        if (top > bottom) {
            break;
        }
        //向上走
        for (int i = bottom; i >= top; i--) {
            temp = matrix[i][left];
            res.add(temp);
        }
        left++;
    }

    return res;
}

}

全部评论

相关推荐

讲原则的小黄鸭不愿吃...:有时候面试眼缘确实很重要,当然,飞驰人生2中张弛说的很对:我努力了无数次,但是我知道机会只会出现在其中一两次。你把每一次笔试面试都全力以赴,总有你运气发挥到位的时候
点赞 评论 收藏
分享
林后润:听说他们有kpi,要到了简历编号就不理人了
27届求职交流
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务