The C++ Program: minesweeper.cpp

  1 /*
  2  * minesweeper.cpp
  3  *
  4  *  Created on: Oct 27, 2009
  5  *      Author: Brianna
  6  */
  7 
  8 #include <iostream>
  9 #include <cstdlib>
 10 #include <string>
 11 #include <vector>
 12 #include <fstream>
 13 using namespace std;
 14 
 15 int main()
 16 {
 17     ifstream infile("files/minesweeper.in");
 18     ofstream outfile("files/minesweeper.out");
 19     
 20         while (true)
 21         {
 22                 int rows, cols;
 23                 infile >> rows >> cols;
 24                 if (rows == 0) return 0;
 25 
 26                 vector<string> board;
 27                 for (int i = 0; i < rows; i++)
 28                 {
 29                         string row;
 30                         infile >> row;
 31                         board.push_back(row);
 32                 }
 33 
 34                 for (int r = 0; r < rows; r++)
 35                 {
 36                         for (int c = 0; c < cols; c++)
 37                         {
 38                                 if (board[r][c] == 'm')
 39                                         continue;
 40 
 41                                 int mines = 0;
 42 
 43                                 for (int newRow = r - 1; newRow <= r + 1; newRow++)
 44                                         for (int newCol = c - 1; newCol <= c + 1; newCol++)
 45                                         {
 46                                                 if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols)
 47                                                         continue;
 48 
 49                                                 if (board[newRow][newCol] == 'm')
 50                                                         mines++;
 51 
 52                                         }
 53                                 board[r][c] = (char)('0' + mines);
 54                         }
 55                 }
 56 
 57                 for (int i = 0; i < rows; i++)
 58                         outfile << board[i] << endl;
 59 
 60         }
 61 
 62 }