2

I am making a Sudoku solver and I cannot manage to get backtracking working by refering to the last element of my list (which holds the positions of the blank spaces).

The code below shows my naive initial approach to this issue:

void solve(int arr[9][9])
{
    position CurrentPos;

    list<position>::iterator j;
    for (j = blankSpaces.begin();  j != blankSpaces.end();  j++)
    {
        CurrentPos.row = j->row;
        CurrentPos.col = j->col;

        for (int i = arr[CurrentPos.row][CurrentPos.col] + 1; i < 10; i++)
        {
            if (valid(arr, CurrentPos, i))
            {
                arr[CurrentPos.row][CurrentPos.col] = i;
                visitedStack.emplace_front(CurrentPos);
            }
            if (!(valid(arr, CurrentPos, i)) && (i == 9))
            {
                j--;
            }
        }
    }

}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

1

You can get the last element of the list by doing the following:

#include <iostream>
#include <iterator>
#include <list>

int main () {
    std::list<int> mylist;
    for (int i = 0; i < 10; i++)
        mylist.push_back (i*10);

    auto last = std::prev(mylist.end());
    std::cout << "The last element is " << *last << '\n';

    return 0;
}

Or you can get the iterator before another iterator by using the same like this:

#include <iostream>
#include <iterator>
#include <list>

int main () {
    std::list<int> mylist;
    for (int i = 0; i < 10; i++)
        mylist.push_back (i*10);

    auto last = std::prev(mylist.end());
    auto prelast = std::prev(last);
    std::cout << "The last element is " << *last << '\n';
    std::cout << "The prelast element is " << *prelast << '\n';

    return 0;
}

Or just use -- as you already do:

#include <iostream>
#include <iterator>
#include <list>

int main () {
    std::list<int> mylist;
    for (int i = 0; i < 10; i++)
        mylist.push_back (i*10);

    auto last = std::prev(mylist.end());
    auto prelast = std::prev(last);
    std::cout << "The last element is " << *last << '\n';
    std::cout << "The prelast element is " << *prelast << '\n';

    prelast--;
    std::cout << "The preprelast element is " << *prelast << '\n';

    return 0;
}
NutCracker
  • 11,485
  • 4
  • 44
  • 68