Counting Neighbours
Check all 8 cells around a position and count the mines.
In Minesweeper, each safe cell shows how many mines surround it. A cell in the middle of the grid has 8 neighbours. A corner cell has only 3. An edge cell has 5. The counting algorithm needs to handle all of these.
The Program
10 CLS
20 PRINT "Counting Neighbours"
30 PRINT
40 DIM m(5, 5)
50 REM place mines at known positions
60 LET m(1, 1) = 9
70 LET m(1, 3) = 9
80 LET m(3, 2) = 9
90 REM count neighbours for cell (2,2)
100 LET r = 2: LET c = 2
110 LET n = 0
120 FOR i = r - 1 TO r + 1
130 FOR j = c - 1 TO c + 1
140 IF i < 1 OR i > 5 THEN GO TO 180
150 IF j < 1 OR j > 5 THEN GO TO 180
160 IF i = r AND j = c THEN GO TO 180
170 IF m(i, j) = 9 THEN LET n = n + 1
180 NEXT j
190 NEXT i
200 PRINT "Grid:"
210 FOR r = 1 TO 5
220 FOR c = 1 TO 5
230 IF m(r, c) = 9 THEN PRINT "*";
240 IF m(r, c) = 0 THEN PRINT ".";
250 NEXT c
260 PRINT
270 NEXT r
280 PRINT
290 PRINT "Cell (2,2) has "; n; " mine neighbours"

How It Works
Lines 60-80 place mines at known positions — (1,1), (1,3), and (3,2). Using fixed positions makes it easy to verify the count by hand.
Line 100 sets the target cell: row 2, column 2. This cell has three mine neighbours.
Lines 120-190 check all 8 neighbours:
120 FOR i = r - 1 TO r + 1
130 FOR j = c - 1 TO c + 1
This visits every cell in a 3x3 block centred on (r,c) — including (r,c) itself.
Lines 140-150 are the boundary guards. If i or j falls outside the grid (less than 1 or greater than 5), skip that cell. Without these checks, m(0,1) or m(2,6) would crash with “Subscript wrong”.
Line 160 skips the centre cell. You don’t want to count the cell itself as its own neighbour.
Line 170 checks for mines. If the neighbour is a mine (value 9), increment the count.
The 3x3 Block
For cell (2,2), the loops check positions (1,1) through (3,3) — all 9 cells in the block. After skipping the centre cell and out-of-bounds positions, the actual neighbours are:
(1,1)* (1,2) (1,3)*
(2,1) [2,2] (2,3)
(3,1) (3,2)* (3,3)
Three cells have mines (marked with *). The count is 3.
Try This
Corner test. Change the target to (1,1). It has only 3 neighbours: (1,2), (2,1), and (2,2). The boundary guards skip everything above and to the left.
Edge test. Try (1,2). It has 5 neighbours (the top row has nothing above it). Verify the count by hand.
What You’ve Learnt
- Neighbour checking — loops from
r-1tor+1andc-1toc+1 - Boundary guards — skip cells outside the array
- Skip self — don’t count the cell you’re checking
- Known data testing — fixed mine positions make verification easy