Khaled Afify
Khaled Afify

Reputation: 35

why this code make infinite loop

i'm trying to test many of test cases for minesweeper game and it causes infinte loop and i didn't get the output

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n,m;
    cin>>n>>m ;

    //cout<<"bug1";
    char grid[n+2][m+2] ;
    string numbers="0123456789" ;
    memset(grid,'0',sizeof grid);

    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
            cin>>grid[i][j];

    //cout<<"bug2";


    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(grid[i][j]!='*'){
                int counter=0;
                for(int ii=i-1;ii<i+2;ii++){
                    for(int jj=j-1;j<j+2;jj++){
                        if(ii>=0 && jj>=0 && grid[ii][jj]=='*')
                            counter++;
                    }
                }
                grid[i][j]=numbers[counter];
            }
        }
    }

    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            cout<<grid[i][j] ;
        }
        cout<<endl ;
    }


    return 0;
}

i try this test case

enter image description here

and it causes infinte loop so ...what is the solution ?

Upvotes: 0

Views: 96

Answers (1)

sjsam
sjsam

Reputation: 21965

j<j+2 // in for(int jj=j-1;j<j+2;jj++){

is always true, the result is infinite loop.

Using real variables like count, total etc makes sense here considering your choice of variables :

i,n,j,m,ii,jj // No wonder if someone is not confused with this.

to name a few.

Upvotes: 6

Related Questions