10189 Minesweeper

Problem Link:10189 Minesweeper

Algorithm:
Every time there are maximum 8 squares for each square.  I used here conditional logic. For each square among 8 square I checked if it is ‘*’. If it is then I increased the count value. Later I replaced the position with that count value.

but there are some problems when the position of the square is in   corner , border side. For that I declared 8 distinct character.  While checking the position of these 8 squares I checked before if this square really exists! if not then I assign the char variable to ‘.’ . if exist then did not bother myself and just assign the character in the declared char variable. After doing this for 8 position(squares). I used condition logic. And searched for ‘*’ character.


#include<cstdio>
#include<cstring>

using namespace std;

int main(){

    int a,b,o=1;

    while(1){

        scanf("%d %d",&a,&b);

        if(a==0 && b==0)
            break;

        if(o>1)
            printf("\n");

        char x[a][b];

        for(int k=0;k<a;k++)
            scanf("%s",x[k]);

        char c,d,e,f,g,h,i,j;

        int cot;

        for(int k=0;k<a;k++){

            for(int l=0;l<b;l++){

                if(x[k][l]!='*'){

                if(k==0 || l==0)
                    c='.';
                else
                    c=x[k-1][l-1];

                if(k==0)
                    d='.';
                else
                    d=x[k-1][l];

                if(k==0 || l==b-1)
                    e='.';
                else
                    e=x[k-1][l+1];

                if(l==b-1)
                    f='.';
                else
                    f=x[k][l+1];

                if(k==a-1 || l==b-1)
                    g='.';
                else
                    g=x[k+1][l+1];

                if(k==a-1)
                    h='.';
                else
                    h=x[k+1][l];

                if(k==a-1 || l==0)
                    i='.';
                else
                    i=x[k+1][l-1];

                if(l==0)
                    j='.';
                else
                    j=x[k][l-1];

                cot=0;

                if(c=='*')
                    cot++;
                if(d=='*')
                    cot++;
                if(e=='*')
                    cot++;
                if(f=='*')
                    cot++;
                if(g=='*')
                    cot++;
                if(h=='*')
                    cot++;
                if(i=='*')
                    cot++;
                if(j=='*')
                    cot++;

                x[k][l]=cot+48;

                }
            }
        }
        printf("Field #%d:\n",o);

        for(int k=0;k<a;k++){
            for(int l=0;l<b;l++){
                printf("%c",x[k][l]);
            }
            printf("\n");
        }
        o++;
    }

    return 0;
}
Advertisements