1
+ package sudoku ;
2
+
3
+ import java .util .Iterator ;
4
+ import java .util .NoSuchElementException ;
5
+
6
+ /**
7
+ * Represents a Sudoku board with support for iteration using the Iterator pattern.
8
+ */
9
+ public class SudokuBoard implements Iterable <SudokuBoard .Cell > {
10
+
11
+ private final int [][] board ;
12
+ private final int size ;
13
+
14
+ public SudokuBoard (int size ) {
15
+ this .size = size ;
16
+ this .board = new int [size ][size ];
17
+ }
18
+
19
+ public int getSize () {
20
+ return size ;
21
+ }
22
+
23
+ public int getValue (int row , int col ) {
24
+ return board [row ][col ];
25
+ }
26
+
27
+ public void setValue (int row , int col , int value ) {
28
+ board [row ][col ] = value ;
29
+ }
30
+
31
+ /** Represents a single cell in the Sudoku board */
32
+ public static class Cell {
33
+ private final int row ;
34
+ private final int col ;
35
+ private final int value ;
36
+
37
+ public Cell (int row , int col , int value ) {
38
+ this .row = row ;
39
+ this .col = col ;
40
+ this .value = value ;
41
+ }
42
+
43
+ public int getRow () {
44
+ return row ;
45
+ }
46
+
47
+ public int getCol () {
48
+ return col ;
49
+ }
50
+
51
+ public int getValue () {
52
+ return value ;
53
+ }
54
+ }
55
+
56
+ /** Iterator implementation for Sudoku board cells */
57
+ private class CellIterator implements Iterator <Cell > {
58
+ private int row = 0 ;
59
+ private int col = 0 ;
60
+
61
+ @ Override
62
+ public boolean hasNext () {
63
+ return row < size && col < size ;
64
+ }
65
+
66
+ @ Override
67
+ public Cell next () {
68
+ if (!hasNext ()) {
69
+ throw new NoSuchElementException ();
70
+ }
71
+ Cell cell = new Cell (row , col , board [row ][col ]);
72
+ col ++;
73
+ if (col == size ) {
74
+ col = 0 ;
75
+ row ++;
76
+ }
77
+ return cell ;
78
+ }
79
+ }
80
+
81
+ @ Override
82
+ public Iterator <Cell > iterator () {
83
+ return new CellIterator ();
84
+ }
85
+ }
0 commit comments