public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        if (matrix.length == 0)
            return res;
        int rowBegin = 0, rowEnd = matrix.length - 1, columnBegin = 0, columnEnd = matrix[0].length - 1;
        while (rowBegin <= rowEnd && columnBegin <= columnEnd) {
            // go right
            for (int i = columnBegin; i <= columnEnd; ++i) {
                res.add(matrix[rowBegin][i]);
            }
            ++rowBegin;
            // go down
            for (int i = rowBegin; i <=rowEnd; ++i) {
                res.add(matrix[i][columnEnd]);
            }
            columnEnd--;
            // go left
            if (rowBegin <= rowEnd) {
                for (int i = columnEnd; i >= columnBegin; --i) {
                    res.add(matrix[rowEnd][i]);
                }
            }
            rowEnd--;
            //go up
            if (columnBegin <= columnEnd) {
                for (int i = rowEnd; i >= rowBegin; --i) {
                    res.add(matrix[i][columnBegin]);
                }
            }
            columnBegin++;
        }
        return res;
    }