B
B
bushmaks2017-10-19 20:19:59
C++ / C#
bushmaks, 2017-10-19 20:19:59

What loop condition is needed to exit the maze?

Hello, I wrote a program to find the exit from the labyrinth (two-dimensional array), but I just can’t come up with a condition for the program to end when it hits the exit coordinates (y=9, x=6).

Program code
#include "iostream"
#include "windows.h"

using namespace std;

int main()
{
  int labirint[10][10] =   //Сам лабиринт
  { { 1,1,1,1,1,1,1,1,1,1 },
  { 1,0,1,1,0,1,0,0,0,1 },
  { 1,0,0,0,0,1,0,1,0,1 },
  { 1,1,1,1,0,1,0,1,0,1 },
  { 1,0,0,0,0,1,0,1,0,1 },
  { 1,1,0,1,1,1,0,1,0,1 },
  { 1,1,0,0,0,0,0,1,0,1 },
  { 1,1,1,1,1,1,1,1,0,1 },
  { 1,0,0,0,0,0,0,0,0,1 },
  { 1,1,1,1,1,1,0,1,1,1 } };
  int direction = 1; //Направление робота
  int y = 0, x = 1; //Координаты робота

  while (1) {   //Цикл, из которого надо выйти при нахождении выхода

    Sleep(1000);
    system("cls");

    labirint[y][x] = 2;   //Указание робота

    for (int i = 0; i < 10; i++) {   //Вывод лабиринта в консоли
      for (int a = 0; a < 10; a++) {
        if (labirint[i][a] == 1) {
          printf("%c", char(219));
        }
        else if (labirint[i][a] == 2) {
          printf("%c", char(253));
        }
        else {
          cout << " ";
        }	
      }
      cout << endl;
    }

    labirint[y][x] = 0; //Очистка хвоста робота
    cout << y << "  " << x << endl;
    switch (direction) {
    case 1: //Вверх
      while (labirint[y][x - 1] == 1 && labirint[y + 1][x] == 0) {
        y++;
      }
      if (labirint[y][x - 1] == 0) {
        direction = 3;
        x--;
      }
      else {
        direction = 2;
      }
      break;
    case 2: //Налево
      while (labirint[y + 1][x] == 1 && labirint[y][x + 1] == 0) {
        x++;
      }
      if (labirint[y + 1][x] == 0) {
        direction = 1;
        y++;
      }
      else {
        direction = 4;
      }
      break;
    case 3: //Направо
      while (labirint[y - 1][x] == 1 && labirint[y][x - 1] == 0) {
        x--;
      }
      if (labirint[y - 1][x] == 0) {
        direction = 4;
        y--;
      }
      else {
        direction = 2;
      }
      break;
    case 4: //Вниз
      while (labirint[y][x + 1] == 1 && labirint[y - 1][x] == 0) {
        y--;
      }
      if (labirint[y][x + 1] == 0) {
        direction = 2;
        x++;
      }
      else {
        direction = 3;
      }
    }
  } 
  system("pause");
    return 0;
}

The algorithm for finding the exit is built on the basis of the rule of one side.
What is the condition to exit the loop?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-10-19
@bushmaks

You must be at a point on the perimeter - this is a set of points with coordinates {x:any,y:0}, {x:any,y:9},{x:0,y:any}, {x:9,y: any}.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question