My JAVA solution


  • 0
    Q
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] result = new int[n][n];
            if (n == 0){
                return result;
            }
            
            int start = 0;
            int end = n-1;
            int val = 1;
            while (start<=end){
                for (int i=start;i<=end;i++){
                    result[start][i]=val;
                    val++;
                }
                for (int i=start+1;i<=end;i++){
                    result[i][end]=val;
                    val++;
                } 
                for (int i=end-1;i>=start;i--){
                    result[end][i]=val;
                    val++;
                }
                for (int i=end-1;i>start;i--){
                    result[i][start]=val;
                    val++;
                }
                start++;
                end--;
            }
            return result;
        }
    }

Log in to reply
 

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