This document describes the conversion of the Same Game from a 2D array grid data structure to a graph-based data structure.
vector<vector<char>> grid; // Stored tile colors
vector<vector<bool>> active; // Stored tile active statusstruct Node {
int row;
int col;
char color;
bool active;
vector<int> neighbors; // indices of adjacent nodes
};
vector<Node> nodes; // Graph nodes
unordered_map<int, unordered_map<int, int>> posToNodeIndex; // Position mappingEach tile is represented as a node in the graph containing:
- Position: (row, col) coordinates
- Color: The tile's color character
- Active: Whether the tile is active or removed
- Neighbors: List of adjacent node indices (up, right, down, left)
The graph is built during initialization:
- Create a node for each tile in the initial grid
- Build position-to-index mapping for efficient lookups
- Establish neighbor relationships between adjacent nodes
BFS traversal now uses the graph structure:
- Start from a node and traverse using neighbor relationships
- No need to check bounds or directions manually
- More efficient neighbor lookups
Gravity is applied by updating node positions:
- Vertical gravity: Move nodes downward by updating row positions
- Horizontal gravity: Shift columns left by updating col positions
- Update neighbors: Rebuild adjacency relationships after position changes
- More intuitive representation: Tiles are explicitly connected as nodes
- Flexible topology: Can support non-rectangular grids in the future
- Efficient neighbor queries: Direct access through neighbor list
- Clear separation of concerns: Position, color, and connectivity are distinct
- Better for algorithms: Graph algorithms naturally apply (BFS, DFS, etc.)
A comprehensive test suite (test_graph.cpp) validates:
- Basic initialization and grid setup
- getTile() and isTileActive() queries
- Cluster detection with BFS
- Cluster removal and gravity
- Score calculation
- User vs Computer mode
- Edge cases (single tiles, invalid positions)
All tests pass successfully, confirming the graph implementation maintains all original functionality.
Compile the test:
g++ -std=c++17 -I. SameGame.cpp test_graph.cpp -o test_graphRun the test:
./test_graphThe public API remains unchanged:
getTile(row, col)- Get tile color at positionisTileActive(row, col)- Check if tile is activegetCluster(row, col)- Get cluster at positionremoveCluster(row, col)- Remove cluster at positionhasMovesLeft()- Check if moves are available
All existing code using the SameGame class continues to work without modifications.