Share my java solution


  • 33
    S
    public static int[][] generateMatrix(int n) {
    	int[][] ret = new int[n][n];
    	int left = 0,top = 0;
    	int right = n -1,down = n - 1;
    	int count = 1;
    	while (left <= right) {
    		for (int j = left; j <= right; j ++) {
    			ret[top][j] = count++;
    		}
    		top ++;
    		for (int i = top; i <= down; i ++) {
    			ret[i][right] = count ++;
    		}
    		right --;
    		for (int j = right; j >= left; j --) {
    			ret[down][j] = count ++;
    		}
    		down --;
    		for (int i = down; i >= top; i --) {
    			ret[i][left] = count ++;
    		}
    		left ++;
    	}
    	return ret;
    }

  • 0
    S

    @Samaritan Make shorter

    public int[][] generateMatrix(int n) {
    	int[][] ret = new int[n][n];
    	int left = -1,top = 0;
    	int right = n -1,down = n - 1;
    	int count = 1;
    	while (left <= right) {
    		for (int j = ++left; j <= right; j++) ret[top][j] = count++;
    		for (int i = ++top; i <= down; i++) ret[i][right] = count++;
    		for (int j = --right; j >= left; j--) ret[down][j] = count++;
    		for (int i = --down; i >= top; i--) ret[i][left] = count++;
    	}
    	return ret;
    }
    

  • 0
    N
            int[][] res = new int[n][n];
            int num = 1;
            for(int layer=0; layer<(n+1)/2; layer++){
                for(int m = layer; m<n-layer; m++){
                    res[layer][m]=num++;
                }
                for(int m = layer+1; m<n-layer-1; m++){
                    res[m][n-1-layer]=num++;
                }
                for(int m =n-layer-1;m>layer; m--){
                    res[n-1-layer][m]=num++;
                }
                for(int m =n-layer-1;m>layer; m--){
                    res[m][layer]=num++;
                }
            }
            return res;
    

Log in to reply
 

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