定義方向: 左上=左|上算法
XxxConstant.h數組
enum{LEFT = 1, RIGHT = (1 << 1), TOP = (1 << 2), BOTTOM = (1 << 3), LEFT_TOP = (LEFT|TOP), RIGHT_TOP=(RIGHT|TOP), LEFT_BOTTOM=(LEFT|BOTTOM), RIGHT_BOTTOM=(RIGHT|BOTTOM)};code
int DIRECTIONS[8] = {LEFT, RIGHT, TOP, BOTTOM, LEFT_TOP, RIGHT_TOP, LEFT_BOTTOM, RIGHT_BOTTOM};get
Cell.h代碼以下: 表示數組元素所在位置 it
#pragma once #include <vector> class Cell { private: int row; int column; int direction; bool exists; public: Cell(int direction):direction(direction){}; Cell(int direction, int row, int column, bool exists):direction(direction), row(row), column(column), exists(exists){}; ~Cell(void); inline int getRow(){ return row; } inline int getColumn(){ return column; } inline int getDirection(){ return direction; } inline bool isExists(){ return exists; } std::vector<Cell*> getSurroundCell(int maxRow, int maxColumn); };
Cell.cpp: Cell::getSurroundCell算法實現io
#include "Cell.h" #include "MineConstant.h" std::vector<Cell*> Cell::getSurroundCell(int maxRow, int maxColumn){ std::vector<Cell*> ret; int direction = 0; if(row > 0){ //不在第一行 direction |= TOP; } if(row < maxRow - 1){ direction |= BOTTOM; } if(column > 0){ direction |= LEFT; } if(column < maxColumn - 1){ direction |= RIGHT; } int directionCount = sizeof(DIRECTIONS) / sizeof(direction); for(int i = 0; i < directionCount; i++){ int direct = DIRECTIONS[i]; Cell* cell = nullptr; if((direction & direct) == direct){ switch (direct) { case LEFT: cell = new Cell(direct, row, column - 1, true); break; case RIGHT: cell = new Cell(direct, row, column + 1, true); break; case TOP: cell = new Cell(direct, row - 1, column, true); break; case BOTTOM: cell = new Cell(direct, row + 1, column, true); break; case LEFT_TOP: cell = new Cell(direct, row - 1, column - 1, true); break; case LEFT_BOTTOM: cell = new Cell(direct, row + 1, column - 1, true); break; case RIGHT_TOP: cell = new Cell(direct, row - 1, column + 1, true); break; case RIGHT_BOTTOM: cell = new Cell(direct, row + 1, column + 1, true); break; default: break; } } if(cell){ ret.push_back(cell); } } return ret; } Cell::~Cell(void) { }