Skip to content

Commit be5ebda

Browse files
committed
Add solution #661
1 parent d010375 commit be5ebda

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,7 @@
497497
657|[Robot Return to Origin](./0657-robot-return-to-origin.js)|Easy|
498498
658|[Find K Closest Elements](./0658-find-k-closest-elements.js)|Medium|
499499
659|[Split Array into Consecutive Subsequences](./0659-split-array-into-consecutive-subsequences.js)|Medium|
500+
661|[Image Smoother](./0661-image-smoother.js)|Easy|
500501
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
501502
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
502503
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|

solutions/0661-image-smoother.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 661. Image Smoother
3+
* https://leetcode.com/problems/image-smoother/
4+
* Difficulty: Easy
5+
*
6+
* An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by
7+
* rounding down the average of the cell and the eight surrounding cells (i.e., the average of the
8+
* nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not
9+
* present, we do not consider it in the average (i.e., the average of the four cells in the red
10+
* smoother).
11+
*
12+
* Given an m x n integer matrix img representing the grayscale of an image, return the image after
13+
* applying the smoother on each cell of it.
14+
*/
15+
16+
/**
17+
* @param {number[][]} img
18+
* @return {number[][]}
19+
*/
20+
var imageSmoother = function(img) {
21+
const result = new Array(img.length).fill().map(() => {
22+
return new Array(img[0].length).fill(0);
23+
});
24+
25+
for (let i = 0; i < img.length; i++) {
26+
for (let j = 0; j < img[0].length; j++) {
27+
let sum = 0;
28+
let count = 0;
29+
for (let di = -1; di <= 1; di++) {
30+
for (let dj = -1; dj <= 1; dj++) {
31+
const ni = i + di;
32+
const nj = j + dj;
33+
if (ni >= 0 && ni < img.length && nj >= 0 && nj < img[0].length) {
34+
sum += img[ni][nj];
35+
count++;
36+
}
37+
}
38+
}
39+
result[i][j] = Math.floor(sum / count);
40+
}
41+
}
42+
43+
return result;
44+
};

0 commit comments

Comments
 (0)