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

char get_at (char ** array, int i, int j, int n, int m) {if (i & Gt; = 0 & amp; i & lt; n & amp; amp; & gt; = 0 & amp; amp; amp; amp; & amp; amp; amp; amp; amp; amp; amp;; & amp; nbsp; m) Return Array [i] [J]; And return '!'; }

This function '!' returns if the index is out of range, it will not be interpreted as a mine.


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -