static void AddNewCellToQ(Cell cell, int deltaRow, int deltaCol) { if (CellIsInAvailable(cell, deltaRow, deltaCol)) { cellsToVisit.Add(new Cell(cell.Row + deltaRow, cell.Col + deltaCol, stepsCounter)); } }
static bool CellIsInAvailable(Cell cell, int deltaRow, int deltaCol) { int newRow = cell.Row + deltaRow; int newCol = cell.Col + deltaCol; bool rowIsValid = newRow >= 0 && newRow < rows; bool colIsValid = newCol >= 0 && newCol < cols; bool visited = true; if (rowIsValid && colIsValid) { visited = board[newRow, newCol] != 0; } return !visited; }
static void BFS(int row, int col) { Queue<Cell> cellsQ = new Queue<Cell>(); Cell startCell = new Cell(row, col, stepsCounter++); cellsQ.Enqueue(startCell); while(cellsQ.Count > 0) { var currentCell = cellsQ.Dequeue(); SetBoardCellValue(currentCell); var availablePositions = GetPossibleNextMoves(currentCell); foreach (Cell cell in availablePositions) { cell.Value = currentCell.Value + 1; cellsQ.Enqueue(cell); } } }
static IList<Cell> GetPossibleNextMoves(Cell cell) { cellsToVisit.Clear(); AddNewCellToQ(cell, -1, -2); AddNewCellToQ(cell, -2, -1); AddNewCellToQ(cell, -2, +1); AddNewCellToQ(cell, -1, +2); AddNewCellToQ(cell, +1, +2); AddNewCellToQ(cell, +2, +1); AddNewCellToQ(cell, +2, -1); AddNewCellToQ(cell, +1, -2); return cellsToVisit; }
static void SetBoardCellValue(Cell cell) { board[cell.Row, cell.Col] = cell.Value; }