首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归回溯不会回溯

递归回溯不会回溯
EN

Stack Overflow用户
提问于 2021-11-17 17:51:21
回答 1查看 224关注 0票数 1

我一直在努力用C++中的隐性回溯来解决以下问题。问题是,它并没有倒退。我在一张纸上手动跟踪我的算法,它在纸上工作。所以问题是我不知道如何在C++中实现这一点。任何帮助都将不胜感激。

问题:

给定一个表示地图高度的二维网格,确定最低点和最高点,以及它们之间是否有一条永不下降的路径。

输入

您的程序将收到以下命令行参数:

代码语言:javascript
复制
<fname> File name for the 2-dimensional map
<M>     Number of rows
<N>     Number of columns

输出

您的程序应该将5个值写入标准输出: Lr Lc Hr Hc YESNO其中Lr Lc是网格中最低点的行和列,Hr Hc是网格中最高点的行和列,YESNO是单词:如果有一条从最低点到最高点的路径永不下降,如果没有这样的路径,则为no。具体来说,路径从最低点开始,只能从一个点到它的四个相邻点(左、右、上、下)中的一个,这些邻居的海拔不低于这个点。输入就会有一个独特的解决方案。

问题在于“路径”函数.

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include<string>
#include <vector>
#include <algorithm>
#include <iostream>
#include<sstream>
// using namespace std;

void ReadFile(std::string fname, std::vector<std::vector<int>> *const vec_2d);

// What about min? row and col are initially the min, but then get updated
void min_max(std::vector<std::vector<int>> *const vec_2d,
             std::vector<int> &vec_1d,
             int num_rows,
             int num_cols,
             int &row,
             int &col,
             int &idx_i_max,
             int &idx_j_max,
             int &cur_val); //grid is vec_2d??????
             
int path(std::vector<int> vec_1d,
         int row,
         int col,
         int num_rows,
         int num_cols,
         int idx_i_max,
         int idx_j_max,
         int &cur_val); // bool *visited is a pointer type bool which could be a 2-d array??
         
int main(int argc, char *argv[])
{
    
    std::vector<std::vector<int>> vec_2d;
    
    std::vector<int> vec_1d;
    // declare variables
    int num_rows, num_cols, row, col, idx_i_max, idx_j_max, cur_val;
    
    std::string fname;
    
    // get .txt file containing the grid
    fname = argv[1]; //string of file name
            
    num_rows = atoi(argv[2]); // convert argument strings to integers
    num_cols = atoi(argv[3]);
    
    // bool visited[100][100];
    //2D vector initialized with user defined size
    // std::vector<std::vector<int>> visited(num_rows, std::vector<int>(num_cols));
    
    ReadFile(fname, &vec_2d); //reading the .txt file and assigning to vec_2d
             
    min_max(&vec_2d,
            vec_1d,
            num_rows,
            num_cols,
            row,
            col,
            idx_i_max,
            idx_j_max,
            cur_val);
    
    path(vec_1d, row, col, num_rows, num_cols, idx_i_max, idx_j_max, cur_val);
}

void ReadFile(std::string fname, std::vector<std::vector<int>> *const vec_2d)
{ //it is a pointer to a vector,therefore, after end of func, it will still exist // Create the input filestream - opens the file & prepares it for reading

    std::ifstream file(fname);
    
    std::string str; // Temporary string to hold a single line of the file
    
    while (std::getline(file, str))
    { // Reads all lines in the file, 1 at at time
    
        std::vector<int> new_row; // Creates a temporary vector to represent one row
        
        std::istringstream ss(str); // Converts our string into a stringstream
        
        int token; // Temp int to store a converted value from a line
        
        while (ss >> token)
        { // Reads all values from the stringstream (current row), converts to int
        
            new_row.push_back(token); // Adds the converted value to the row
        }
        
        vec_2d->push_back(new_row); // Pushes our constructed vector of ints to the 2D vector
    }
}

void min_max(std::vector<std::vector<int>> *const vec_2d,
             std::vector<int> &vec_1d,
             int num_rows,
             int num_cols,
             int &row,
             int &col,
             int &idx_i_max,
             int &idx_j_max,
             int &cur_val)
{ //I dont need any argument for this func

    //Converting 2-d vec to 1-d to find loc of min and max
    
    for (int i = 0; i < (*vec_2d).size(); i++)
    {
        
        for (int j = 0; j < (*vec_2d)[i].size(); j++)
        {
            
            vec_1d.push_back((*vec_2d)[i][j]);
        }
    }
    // finding the max and min values in the grid vector and save thier index (max_idx and min_idx)
    int max_idx, min_idx; // Initialize two int for index of max and min values
            
    // 
    int maxElementIndex = std::max_element(vec_1d.begin(), vec_1d.end())
            - vec_1d.begin(); //max elem index //I need to convert 2d to 1d vector to use this func
            
    int minElementIndex = std::min_element(vec_1d.begin(), vec_1d.end())
            - vec_1d.begin(); //min elem index
            
            //convert 1-d  vec idx to 2-d vec idx
    idx_i_max = (maxElementIndex / num_cols) + 1; //actual idx + 1
            
    idx_j_max = (maxElementIndex % num_cols) + 1; //actual idx + 1
            
    int idx_i_min = (minElementIndex / num_cols) + 1; //actual idx + 1
            
    int idx_j_min = (minElementIndex % num_cols) + 1; //actual idx + 1
            
    //      The initial current value is the minimum
    cur_val = *std::min_element(vec_1d.begin(), vec_1d.end());
    
    //loc of min will be our start point as below
    row = idx_i_min; //actual idx + 1
            
    col = idx_j_min; //actual idx + 1
            
    // print i and j idx of min and max respectively (with a space after each)
    
    std::cout << idx_i_min << " ";
    
    std::cout << idx_j_min << " ";
    
    std::cout << idx_i_max << " ";
    
    std::cout << idx_j_max << " "; //This prints are working fine
            
    // A recursive backtracking function to go over all cells. base case is when all directions are impossible, then retuen 0
}
//row and col will be changed in every recursion. should they be const???
int path(std::vector<int> vec_1d,
         int row,
         int col,
         int num_rows,
         int num_cols,
         int idx_i_max,
         int idx_j_max,
         int &cur_val)
{
    
    //  std::cout<<"test"<<std::endl;
    
    std::cout << std::endl << row << " " << col << std::endl; // it atops at the second cell
            
    // std::cout<<cur_val<<std::endl;//it prints the start point twice
    
    // if the evaluating neighbor cell is equal to max value
    if (row == idx_i_max && col == idx_j_max)
    { //base case
    
        std::cout << "yes";
        
        return 1;
    }
    
    else
    {
        
        cur_val = vec_1d[((row - 1) * num_cols) + (col - 1)]; //updating the current value  
                
        //Checking the north neighbor (COND1)
        if (row - 1 > 0
                && vec_1d[((row - 1 - 1) * num_cols) + (col - 1)] >= cur_val)
        { //if the north cell is -1
        
            vec_1d[((row - 1) * num_cols) + (col - 1)] = -1; // making the current cell as visited
                    
            path(vec_1d,
                 row - 1,
                 col,
                 num_rows,
                 num_cols,
                 idx_i_max,
                 idx_j_max,
                 cur_val);
            
            return 1;
        }
        
        //Checking the south neighbor(COND2)
        if (row + 1 <= num_rows
                && vec_1d[((row + 1 - 1) * num_cols) + (col - 1)] >= cur_val)
        {
            
            vec_1d[((row - 1) * num_cols) + (col - 1)] = -1;
            
            path(vec_1d,
                 row + 1,
                 col,
                 num_rows,
                 num_cols,
                 idx_i_max,
                 idx_j_max,
                 cur_val);
            return 1;
        }
        
        //Checking the west neighbor(COND3)
        if (col - 1 > 0
                && vec_1d[((row - 1) * num_cols) + (col - 1 - 1)] >= cur_val)
        {
            
            vec_1d[((row - 1) * num_cols) + (col - 1)] = -1;
            
            path(vec_1d,
                 row,
                 col - 1,
                 num_rows,
                 num_cols,
                 idx_i_max,
                 idx_j_max,
                 cur_val);
            
            return 1;
        }
        
        //Checking the east neighbor(COND4)
        if (col + 1 <= num_cols
                && vec_1d[((row - 1) * num_cols) + (col + 1 - 1)] >= cur_val)
        {
            
            vec_1d[((row - 1) * num_cols) + (col - 1)] = -1;
            
            path(vec_1d,
                 row,
                 col + 1,
                 num_rows,
                 num_cols,
                 idx_i_max,
                 idx_j_max,
                 cur_val);
            
            return 1;
        }
        
        // return 0;
        
    }
    // FORGET ABOUT PRINTING YES/NO. FOCUS ON THE PRINT OF CURRENT CELL
    // if(path){
    
    //         std::cout<<"yes";
    // }
    // else{
    
    //         std::cout<<"no";
    // }
}

EN

回答 1

Stack Overflow用户

发布于 2021-11-17 21:49:24

以下是一个提示:

代码语言:javascript
复制
^ g++ Foo.cpp -Wall --std=c++17 -o Foo
Foo.cpp: In function ‘void min_max(std::vector<std::vector<int> >*, std::vector<int>&, int, int, int&, int&, int&, int&, int&)’:
Foo.cpp:107:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     for (int i = 0; i < (*vec_2d).size(); i++)
                     ~~^~~~~~~~~~~~~~~~~~
Foo.cpp:110:27: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
         for (int j = 0; j < (*vec_2d)[i].size(); j++)
                         ~~^~~~~~~~~~~~~~~~~~~~~
Foo.cpp:117:9: warning: unused variable ‘max_idx’ [-Wunused-variable]
     int max_idx, min_idx; // Initialize two int for index of max and min values
         ^~~~~~~
Foo.cpp:117:18: warning: unused variable ‘min_idx’ [-Wunused-variable]
     int max_idx, min_idx; // Initialize two int for index of max and min values
                  ^~~~~~~
Foo.cpp: In function ‘int path(std::vector<int>, int, int, int, int, int, int, int&)’:
Foo.cpp:273:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

在编译中添加-Wall标志将告诉编译器帮助您发现愚蠢的错误。我会修正这些警告,看看你的问题是否消失。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70009273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档