使用C ++从.txt解决迷宫

时间:2013-12-03 14:30:43

标签: c++ text fstream dynamic-arrays maze

所以,我正在研究一个代码,该代码应该解决在.txt文件中给出的迷宫,让我们说“input.txt”,其中1's = blocks,0's =开放路径,形式如下:

Maze1
7,6 //Number of rows and columns of the maze: row,column
1,1,1,1,1,1
1,0,1,1,0,1
1,0,0,0,0,1
1,0,1,1,0,0
1,0,1,1,0,1
1,1,0,0,1,1
1,1,1,1,1,1
1 // number of entrances
1,2 // coordinate of an entrance relative to the origin: row, column

所以我脑子里有一些算法,但是让我们说“第一”入口是无效的......

所以输出应该是这样的:

Maze1
Entrance: 1,2 Invalid

这应该打印在另一个.txt文件中,让我们说“Output.txt”....但它实际上没有给我任何语法错误,但它没有写任何东西到Output.txt ...

无论如何,这是我的“不完整代码”...所以请帮助我:

#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;


struct Stack
{
    int data[30]; //X should be constant
    int top;
}; //Stack

void Push(int a,Stack &S)
{
    S.top++;

    if (S.top>=30) //Remember X should be constant
    {
        cout<<"The stack is full!"<<endl;
        S.top--;
        return;
    }

    else
    {
        S.data[S.top]=a;
    }
} //Push

int Pop(Stack &S)
{
    if (S.top==-1)
    {
        cout<<"The stack is empty!"<<endl;
        return 0;
    }

    else
    {
        int Temp=S.data[S.top];
        S.data[S.top]=NULL;
        S.top--;
        return Temp;
    }
} //Pop





int main ()
{
    #define false 1;
    #define true 0;
    string line;
    Stack s1 = { NULL, -1 }, s2 = { NULL, -1 };
    int x, y;   //Dimensions of Matrix.
    int z;      //Element Location in Matrix.
    int a;      //Number of Entrance Points.
    int b, c;   //Coordinates of Entrance Points.
    char ch;   //Comma indication.

    ifstream input ("Input.txt");   //Using relative addresses.
    ofstream output ("Output.txt");

    input>>line;
    cout<<"Solution for "<<line<<" : \n \n \n";
    input>>x>>ch>>y;                //Reading the Dimensions of the Matrix.
    cout<<line<<" coordinates are "<<x<<ch<<y<<endl<<endl<<endl;

    int **Maze = new int *[x];      //Creating Dynamic Matrix.
    for (int i=0; i<x; i++)
    {
        Maze[i]= new int [y];
    }


    for (int i=0; i<x; i++)         //Filling the Maze from the .txt
    {
        for (int j=0; j<y; j++)
        {
            input>>z;
            Maze[i][j]=z;
        }
    }


    input>>a;                       //Reading the number of entrances.
    for(int i=0; i<a; i++)  
    {
        input>>b>>ch>>c;            //Reading the entrance coordinates.
        if (Maze[b][c]==1 || b>7 || c>6)   //Checking for the validity of entrance point.
        {
            cout<<"Entrance: "<<b<<ch<<c<<"    is Invalid! \n";
            output<<"Entrance: "<<b<<ch<<c<<"    is Invalid! \n";// WRITE ENTRANCE IS INVALID IN OUTPUT FILE
        }

    }



    output.close();
    input.close();


    for(int i=0; i<x; i++)          //Deleting Maze
    {
        delete[] Maze[i];
    }
    delete[] Maze;



  return 0;
}

那么错误在哪里?

1 个答案:

答案 0 :(得分:1)

C ++中的数组是0索引的 - 也就是说,Maze[1][2]是第二行第三列中的单元格。对输入文件中的入口单元格进行编号,或者从代码中的每个co-ord中减去1。

此外,在解析迷宫本身时,您似乎没有考虑逗号。