Java uses 3 for loops


  • 0
    A

    The third for loop is to prevent too many if statement.

    class Solution {
        public int[][] imageSmoother(int[][] M) {
            int[][] N = new int[M.length][M[0].length];      
            int i;
            int j;
            int x;
            int y;
            int p;
            int count; 
            int sum;
            for (i = 0; i < M.length; i++) {
                for (j = 0; j < M[i].length; j++) {
                    count = 0;
                    sum = 0;
                    for (p = 0; p < 9; p++) {
                        x = p / 3 + i - 1;
                        y = p % 3 + j - 1;
                        if(x >= 0 && x < M.length && y >= 0 && y < M[i].length) {
                            count++;
                            sum += M[x][y];
                        }
                    }
                    N[i][j] = sum / count;
                }
            }
            return N;
        }
    }
    

Log in to reply
 

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