simple C solution


  • 0
    W
    int** imageSmoother(int** M, int MRowSize, int MColSize, int** columnSizes, int* returnSize) {
        int **ret=(int **)malloc(MRowSize*sizeof(int*));
        *columnSizes=calloc(MRowSize,sizeof(int));
        for(int i=0;i<MRowSize;i++){
        	ret[i]=calloc(MColSize,sizeof(int));
        	(*columnSizes)[i]=MColSize;
        	for(int j=0;j<MColSize;j++){
        		int sum=M[i][j];
        		int count=1;
        		for(int k=0;k<8;k++){
        			switch(k){
        				case 0:
        					if(j-1>=0) {sum+=M[i][j-1];count++;}
        					break;
        				case 1:
        					if(i-1>=0&&j-1>=0) {sum+=M[i-1][j-1];count++;}
        					break;
        				case 2:
        					if(i-1>=0) {sum+=M[i-1][j];count++;}
        					break;
        				case 3:
        					if(i-1>=0&&j+1<MColSize) {sum+=M[i-1][j+1];count++;}
        					break;
        				case 4:
        					if(j+1<MColSize) {sum+=M[i][j+1];count++;}
        					break;
        				case 5:
        					if(i+1<MRowSize&&j+1<MColSize) {sum+=M[i+1][j+1];count++;}
        					break;
        				case 6:
        					if(i+1<MRowSize) {sum+=M[i+1][j];count++;}
        					break;
        				case 7:
        					if(i+1<MRowSize&&j-1>=0) {sum+=M[i+1][j-1];count++;}
        					break;
        			}
        		}
        		ret[i][j]=sum/count;
        	}	
        }
        * returnSize=MRowSize;
        return ret;
    }
    

  • 0
    W

    Another C solution,simpler!

    int** imageSmoother(int** M, int MRowSize, int MColSize, int** columnSizes, int* returnSize) {
        int **ret=calloc(MRowSize,sizeof(int*));
        *columnSizes=calloc(MRowSize,sizeof(int));
        for(int i=0;i<MRowSize;i++){
            ret[i]=calloc(MColSize,sizeof(int));
            (*columnSizes)[i]=MColSize;
            for(int j=0;j<MColSize;j++){
                int sum=0,count=0;
                int xmin=fmax(i-1,0),xmax=fmin(i+1,MRowSize-1);
                int ymin=fmax(j-1,0),ymax=fmin(j+1,MColSize-1);
                for(int x=xmin;x<=xmax;x++){
                    for(int y=ymin;y<=ymax;y++){
                        sum+=M[x][y];
                        count++;
                    }
                }
                ret[i][j]=sum/count;
            }   
        }
        * returnSize=MRowSize;
        return ret;
    }
    

Log in to reply
 

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