用C ++打印4x4网格上的移动步骤

时间:2016-01-29 01:37:09

标签: c++

我正在用C ++编写这个程序,我必须打印出一个4x4网格,并要求用户输入(x,y)值和结束(x,y)值。

我希望程序做的是在用户想要它开始的网格上打印出x,然后打印出它到结束点的路径。我已准备好网格的打印功能,现在我只需要弄清楚如何让网格打印每一步。

x只能向上,向左,向右和向下移动,因此没有对角线移动。我还希望前面的x保留在每一步打印出的下一个网格中。

编辑:

这是我到目前为止的代码:

#include <iostream>

using namespace std;

void print_grid(){

    cout << "  _______________ " << endl;
    cout << "1|___|___|___|___|" << endl;
    cout << "2|___|___|___|___|" << endl;
    cout << "3|___|___|___|___|" << endl;
    cout << "4|___|___|___|___|" << endl;
    cout << "   1   2   3   4  " << endl;
}

void find_path(int xStart, int yStart, int xEnd, int yEnd){
        print_grid();
}


int main(){
    int xStart, yStart, xEnd, yEnd;

    cout << "Welcome to the rover control panel." << endl;
    cout << "Your options for movement are on a 4x4 grid with x-values 1 through 4 and y-values 1 through 4." << endl;
    cout << "Where would you like to start the rover out?" << endl;
    cout << "Enter your starting x coordinate: " << endl;
    cin >> xStart;
    cout << "Enter your starting y coordinate: " << endl;
    cin >> yStart;
    cout << "Enter your ending x coordinate: " << endl;
    cin >> xEnd;
    cout << "Enter your ending y coordinate: " << endl;
    cin >> yEnd;

return 0;
}

2 个答案:

答案 0 :(得分:0)

我会做这样的事情:

void print_grid(std::vector<int> cells_in_path){

    cout << "  _______________ " << endl;
    int i_cell = 0; char c;
    for (int row = 1; row <= 4; row++){
        cout << row;
        for (int col = 1; col <= 4; col++, i_cell++){

            // checking if current cell presents in path
            if (std::find(vector.begin(), vector.end(), item) != vector.end())
                c = 'x';
            else
                c = '_';
            cout << "|_" << c << "_";
        }
        cout << "|" << endl;
    cout << "   1   2   3   4  " << endl;

    return;
}

这里std::vector<int> cells_in_path是路径中包含的单元索引的向量(索引从0到15)。然后,您应该在cells_in_path内填写find_path(...) - 一步一步或全部填写,然后自行决定。

如果它是C ++,那么我会将这些函数作为一个类中的方法。

答案 1 :(得分:0)

int start_x, start_y, finish_x, finish_y = 0;

start_x = 0;
start_y = 3;

finish_x = 3;
finish_y = 1;

cout << "+------------+\n";

for(int i = 0; i < 4; i++)
{
    cout << "|";

    for(int j = 0; j < 4; j++)
    {
        // start point
        if(j == start_x && i == start_y)
        {
            cout << " S ";
        }
        // finish point
        else if(j == finish_x && i == finish_y)
        { 
            cout << " F ";
        }
        else
        {
            cout << " _ ";
        }
    }

    cout << "|";

    cout << endl;
}
cout << "+------------+\n";

输出:

+------------+
| _  _  _  _ |
| _  _  _  F |
| _  _  _  _ |
| S  _  _  _ |
+------------+

这是显示器。你最好用'_'创建一个二维数组,然后改变开始和结束的位置。至于路径,你要检查开始的x和y是否大于或小于结束的x和y并相应地移动。如果你想要花哨的话,可以使用while循环或递归来完成它。