c++ - Minesweeper Code error -
#include & lt; Iostream & gt; #to & lt include, vector & gt; #include & lt; string & gt; # Include & lt; Algorithm & gt; using namespace std; Int main () {int n, m, counter = 0 ;; CIN & gt; & Gt; N & gt; & Gt; Meter; Four x [n] [m]; Int y [n] [m]; For (int i = 0; i & lt; n; i ++) {for (int j = 0; j & lt; m; j ++) {cin & gt; & Gt; X [i] [j]; // array input}} (int i = 0; i & lt; n; i ++) {for (int j = 0; j & lt; m; j ++) {counter = 0; If (x [ii] [j] == '.') // search for mines (*) {if (x [i] [j-1] == '*') counter ++; If (x [ii] [j + 1] == '*') counter ++; If (x [I-1] [J] == '*') counter ++; If (x [i + 1] [j] == '*') counter ++; If (x [I + 1] [J-1] == '*') Counter ++; If (x [i + 1] [j + 1] == '*') counter ++; If (X [I-1] [J-1] == '*') Counter ++; If (X [I-1] [J + 1] == '*') Counter ++; } If (x [ii] [j]! = '*') Y [i] [j] = counter; // Assign other values y [i] [j] = '*'; }} For (int i = 0; i & lt; n; i ++) {for (int j = 0; j & lt; m; j ++) {if (y [i] [j] == 42) cout & lt; & Lt; '*'; And cout & lt; & Lt; Y [i] [j]; // Output numeric array} cout & lt; & Lt; Endl; } Return 0; } This is Minesweeper code which has input
4 4 * ... .... .... .... ... . and output
* 100 2210 1 * 10 1110 but code output
* 101 2210 1 * 10 1110 Turns to zero in the top right What does this do?
And there is one more easy way to find mines (*) without all conditions?
You are reading beyond the memory of the array. When you are on line 0..n-2, you are reading in line, line n-1 , you are reading unreadable memory.
Check that the memory you are using is under proper lines and the array is within range.
Ie
if (x [i] [j + 1] == '*') What if < Code> j == m-1 ?
if (x [i-1] [j] == '*') what if i == 0 ?
The problem is basically two fixes First of all, you can check that i, j are in range, say
if (j & lt; m - 1 & amp; amp; x [i] [j + 1] == '*') this will solve the problem, but Code reuse is bad from perspective. I will write a function, say
Comments
Post a Comment