← Back to Graphs Part 1

Check Neighbors

4 of 9

Exercise 3: Check Neighbors

Your Task

Write a function count_neighbors(grid, row, col, value) that returns how many of the 4 adjacent cells (up, down, left, right) equal value.

Be careful at the edges — don't go out of bounds!


Examples

grid = [ [1, 2, 1], [2, 5, 2], [1, 2, 1] ] print(count_neighbors(grid, 1, 1, 2)) # 4 — all 4 neighbors of center are 2 print(count_neighbors(grid, 0, 0, 2)) # 1 — top-left corner, only right neighbor is 2 print(count_neighbors(grid, 1, 1, 1)) # 0 — center has no neighbors equal to 1

Hints

Try it yourself

Code: Check Neighbors

Loading Python runtime…
Python …
Loading...
bash
$ Click "Run" to execute your code...