mardi 3 décembre 2019

C++ program with 2D array problem with path planning

I've written this code which plans a path taken according to the 2D array the user inputs. For instance, if the height and width values are 5 and 5, and the user inputs the following 5*5 array:

-1 -1 -1  -1 -1
-1  0  0  0 -1
-1  1 -1 -2 -1
-1  0 -1  0 -1
-1 -1 -1  -1 -1

Here, -1s are blocks and 0s are free spaces. The code finds the '1', and turns the 0s to the top, bottom, left and right to 2.Then the code finds the 2s and converts adjacent 0s to 3s, and so on. Finally, the number adjacent to the '-2' is the output we want to extract.In the case above, '4' is the expected output. My code seems logically correct to me, although it is simplified and I havent added any functions yet. I am not yeilding the correct output and cannot figure out why

I would be super grateful for any help!



#include <iostream>

using namespace std;

const int MAX_SIZE = 1000;


int main()
{
  int map_h;
  int map_w;
  bool invalid=false;
  bool is0 = false, is1=false, is_2 = false;
  cin >> map_h >> map_w;

  int map[MAX_SIZE][MAX_SIZE];

  // initialize map
  for (int i=0; i<MAX_SIZE; i++){
    for (int j=0; j<MAX_SIZE; j++){
      map[i][j] = -1;
    }
  }

  // read map from standard input
  for (int i=0; i<map_h; i++){
    for (int j=0; j<map_w; j++){
      cin >> map[i][j];
    }
  }
  //checks if array has 0s, 1s and -2s in it
  for(int i=0;i<map_h;i++){
    for (int j=0; j<map_w; j++){

        if (map[i][j] == 0){
            is0 = true;
        }
        if (map[i][j] == 1){
            is1 = true;
        }
        if (map[i][j] == -2){
            is_2 = true;
        }

    }
  }

if (not((is0==true) && (is1==true) && (is_2 == true))) {
  invalid = true;
}    


int numtofind=0;  //This is the output variable
int counter=1;
for(int i=0;i<map_h;i++){
    for(int j=0; j<map_w; j++){
        if (map[i][j] == counter){

            if (map[i-1][j]==0){
                map[i-1][j]=counter+1;


            }
            if(map[i+1][j]==0){
                map[i+1][j]=counter+1;
            }
            if(map[i][j-1]==0){
                map[i][j-1]=counter+1;
            }
            if(map[i][j+1]==0){
                map[i][j+1]=counter+1;
            }
            if((map[i-1][j]==-2)||(map[i+1][j]==-2)||(map[i][j-1]==-2)||(map[i][j+1]==-2)){
                numtofind=counter;
                break;
            }
            counter=counter+1;

        }

  }
  }


if(invalid==true){
    cout<<"No"<<endl;
}else{
    cout<<numtofind<<endl;
    }



return 0;
}

Aucun commentaire:

Enregistrer un commentaire