My accepted code. Can anyone solve the problem without initiating the matrix to be all zeros?


  • -1
    J
    vector<vector<int> > generateMatrix(int n) {
        vector<int> tmp;
        vector<vector<int>> matrix;
        int i;
        for(i=0;i<n;i++) tmp.push_back(0);
        for(i=0;i<n;i++) matrix.push_back(tmp);
        int val = 1,edge = 0;
        while(val<=n*n){
            for(i=edge;i<n-edge;i++){
                matrix[edge][i]=val++;
            }
            for(i=edge+1;i<n-edge;i++){
                matrix[i][n-edge-1]=val++;
            }
            for(i=n-edge-2;i>=edge;i--){  
                matrix[n-edge-1][i]=val++;
            }
            for(i=n-edge-2;i>=edge+1;i--){
                matrix[i][edge]=val++;
            }
            edge++;
        }
        return matrix;
    }

  • -1
    C

    here is my Java solution Based on recursion

    public class Solution {
    public int[][] generateMatrix(int n) {
        int [][] u = new int[n][n];
        solve(u,1,0,n);
        return u;
    }
    void solve(int [][] u , int num , int start , int end)
    {
        if(start >= end)return;
        for(int i = start ; i < end ; i++)
            u[start][i] = num++;
        for(int i = start +1 ; i < end ; i++)
            u[i][end-1]= num++;
        for(int i = end-2 ; i >= start ; i--)
            u[end-1][i] = num++;
        for(int i = end-2 ; i > start ; i--)
            u[i][start]=num++;
        solve(u , num , start+1 , end-1);
    }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.