My Recursive Java Solution, Easy understanding


  • 0
    G
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] result = new int[n][n];
            fill(result,0,0,n);
            return result;
            
        }
        public void fill(int[][] n,int base,int circle,int m){//m means the n in inside matrix
            if(m <= 0)  return;
            int width = n.length;
            for(int i = circle; i< width-circle;i++){
                n[circle][i] = base + i + 1;
                n[width-circle-1][width-i-1] = base + 2*m -1 + i;
            }
            for(int i = circle+1;i<width-circle-1;i++){
                n[i][width - circle -1] = n[i-1][width-circle-1]+1;
                n[width-i-1][circle] = n[width-i][circle]+1;
            }
            fill(n, base + 4*m-4 -1,circle+1,m-2);
            return;
        }
    }

Log in to reply
 

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