题解 | #螺旋矩阵#

螺旋矩阵

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

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> ans = new ArrayList<>();
        int top,bottom,right,left,i;
        
        if(matrix.length==0)return ans;
        
        top = 0;
        bottom = matrix.length-1;
        left = 0;
        right = matrix[0].length - 1;

        while(top< (matrix.length+1)/2&&left< (matrix[0].length+1)/2){
            for(i=left;i<=right;i++)ans.add(matrix[top][i]);
            for(i=top+1;i<=bottom;i++)ans.add(matrix[i][right]);
            for(i=right-1;top!=bottom&&i>=left;i--)ans.add(matrix[bottom][i]);
            for(i=bottom-1;right!=left&&i>=top+1;i--)ans.add(matrix[i][left]);
            top++;
            bottom--;
            right--;
            left++;
        }
        return ans;
    }

}
全部评论

相关推荐

06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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