leetcode: 59题

给你一个正整数 n ,生成一个包含 1n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

C# :

public class Solution {
    public int[][] GenerateMatrix(int n) {
          int[][] result = new int[n][];
        for(int p=0;p<n;p++)
        {
            result[p]=new int[n];
        }
        int startx=0;
        int starty=0;
        int offset = 1;
        int count = 1;
        int i=0;
        int j=0;
        //要转的圈数
        
        while(count < n*n)
        {
            j=startx;
            i=starty;
            for(;j<n-offset;j++)
            {
                result[i][j] = count++;
            }
            for(;i<n-offset;i++)
            {
                result[i][j] = count++;
            }

            for(;j>=offset ;j--)
            {
                result[i][j] = count++;
            }
            for(;i>=offset ;i--)
            {
                result[i][j] =count++;
            }
            startx++;
            starty++;
            offset++;
        }

        if(n%2 == 1)
        {
            result[n/2][n/2]=count;
        }
        return result;
    }
}

rust

impl Solution {
    pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> {
   let mut result:Vec<Vec<i32>> =Vec::with_capacity(n as usize);
    for _ in 0..n
    {
        let mut  row = Vec::with_capacity(n as usize);
        for _ in 0..n
        {
            row.push(0);
        }
        result.push(row);
    }
    let mut count =1;
    let mut i;
    let mut j;
    let mut offset = 1;
    let mut startx=0;
    let mut starty=0;
    while count < n*n
    {
        i = starty;
        j = startx;
        while j < n-offset 
        {
            result[i as usize][j as usize] = count;
            count+=1;
            j+=1;
        }
        while i < n - offset 
        {
            result[i as usize][j as usize] = count;
            count += 1;
            i+=1;
        }

        while j >= offset 
        {
            result[i as usize][j as usize] = count;
            count +=1;
            j-=1;
        }
        while i >= offset
        {
            result[i as usize][j as usize] = count;
            count +=1;
            i -= 1;
        }
        startx +=1;
        starty +=1;
        offset +=1;
    }
    if n%2 == 1
    {
        result[(n/2) as usize ][(n/2) as usize] = count;
    }
    result
 }
}