The median filter wipes out salt-and-pepper noise and keeps edges sharp.
What to build
A program that applies a k × k median filter to every pixel.
Requirements
- Each pixel becomes the middle value of the sorted k × k window centred on it.
- Outside the image, use replicate padding: copy the nearest edge pixel.
- Print H rows of W values.
Input
Line 1: H, W and k (odd). Then H rows of W values.
Output
H rows.
Constraints
1 ≤ H, W ≤ 40; k is 1, 3 or 5.
Example
Input:
3 3 3
10 10 10
10 255 10
10 10 10
Output:
10 10 10
10 10 10
10 10 10
Why it works
Extreme values fall to the ends of the sorted window, so the middle value comes from the majority of the neighbourhood; clamping the indices gives border pixels a full window too.
Examples
Example 1 · Input
3 3 3 10 10 10 10 255 10 10 10 10
Expected output
10 10 10 10 10 10 10 10 10
Example 2 · Input
1 5 3 5 0 5 9 5
Expected output
5 5 5 5 5
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For pixel (r, c), read rows r − m to r + m and columns c − m to c + m with m = k // 2, clamping each index into the image.
Hint 2
Sort the k × k values; the median is at index (k × k) // 2.
Solution
Show one correct solution (try it yourself first)
h, w, k = map(int, input().split())
img = [list(map(int, input().split())) for _ in range(h)]
m = k // 2
for r in range(h):
out = []
for c in range(w):
win = sorted(img[min(max(r + i, 0), h - 1)][min(max(c + j, 0), w - 1)] for i in range(-m, m + 1) for j in range(-m, m + 1))
out.append(win[len(win) // 2])
print(" ".join(map(str, out)))