Java, simple and clear, easy understood


  • 8
    public class Solution {
        public int[][] generateMatrix(int n) {
            // similar to spiral matrix I,done by myself
            int[][] rs = new int[n][n];
            int top = 0,bottom = n-1,left = 0,right = n-1;
            int num = 1;
            
            while(left<=right && top <=bottom){
                for(int i=left;i<=right;i++){
                    rs[top][i] = num++;
                }
                top++;
                for(int i= top;i<=bottom;i++){
                    rs[i][right] = num++;
                }
                right--;
                for(int i= right;i>=left;i-- ){
                    rs[bottom][i] = num++;
                }
                bottom--;
                for(int i = bottom;i>=top;i--){
                    rs[i][left] = num++;
                }
                left++;
            }
            return rs;
        }
    }

  • 0
    J

    Good solution!


  • 0

    @jguo11 Thank you:)


  • 0
    A

    wa~amazing!Good~Thx~


  • 0

    @AGuiCode Thank you and good luck!


  • 0

    Implement in Python

    class Solution(object):
        def generateMatrix(self, n):
            matrix = [[0] * n for _ in range(n)]
            if n == 0:
                return matrix
            rowBegin, colBegin, rowEnd, colEnd = 0, 0 , n - 1, n - 1
            num = 1
            while rowBegin <= rowEnd and colBegin <= colEnd:
                for i in range(colBegin, colEnd + 1):
                    matrix[rowBegin][i] = num
                    num += 1
                rowBegin += 1
                for j in range(rowBegin, rowEnd + 1):
                    matrix[j][colEnd] = num
                    num += 1
                colEnd -= 1
                for i in range(colEnd, colBegin - 1, -1):
                    matrix[rowEnd][i] = num
                    num += 1
                rowEnd -= 1
                for j in range(rowEnd, rowBegin - 1, -1):
                    matrix[j][colBegin] = num
                    num += 1
                colBegin += 1
            return matrix
    

Log in to reply
 

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