九宫格中的每个「宫」作为静态内部类定义为 Cell,每个 Cell 包括两个坐标,即行(row)和列(column),row 和 column 的范围均在 [0, 3) 内。这样定义的好处,一是利用矩阵的思想来表示九宫格,二是可以把「row 3 + column*」作为 Cell 的值,用 0~8 共 9 个数字来表示九宫格。比如,绘制的路径是 「L」 型,就可以用「03678」来表示这个路径。
public static final class Cell { final int row; final int column; // keep # objects limited to 9 private static final Cell[][] sCells = createCells(); private static Cell[][] createCells() { Cell[][] res = new Cell[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { res[i][j] = new Cell(i, j); } } return res; } /** * @param row The row of the cell. * @param column The column of the cell. */ private Cell(int row, int column) { checkRange(row, column); this.row = row; this.column = column; } public int getRow() { return row; } public int getColumn() { return column; } public static Cell of(int row, int column) { checkRange(row, column); return sCells[row][column]; } private static void checkRange(int row, int column) { if (row < 0 || row > 2) { throw new IllegalArgumentException("row must be in range 0-2"); } if (column < 0 || column > 2) { throw new IllegalArgumentException("column must be in range 0-2"); } } @Override public String toString() { return "(row=" + row + ",clmn=" + column + ")"; } }