why is my global variable not updating?

I apologize for this long code. The code is called the "Knight's Tour" in which a knight must traverse through each square of a chessboard.

A global variable known as knightPos indicate either -1 or a number of step the knight takes; knightPos returns -1 if a square (all squares are marked -1 initially) and or returns the lasts position of the knight (indicated by the knight's # of steps)

Expectation: the knight should not traverse a square that doesnt have -1.
Reality: the knight traversed a square marked 1 on the 2nd iteration of a loop; because knightPos is returning -1 even though I stored the last position of the knight on it.

The code prints out a .txt file that tracks the movements of the knight; one will see that on the 2nd iteration of a loop, the knight goes back to one of its squares, which it already traversed, which is an undesirable condition.

The reason is that knightPos is returning -1 and not updating, thus it is returning true for my if statement and allows the knight to move there.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
Code:

<

#include <iostream>
#include <fstream> 
#include <iomanip> 

using namespace std;

int n[2];
int brdSize;
int usrSize; 

//array of moves 
int horizontal[8] = {2,  2, -2, -2, 1,  1, -1, -1};
int vertical[8]   = {1, -1,  1, -1, 2, -2,  2, -2};

int scanHorizon, scanVertical;
int steps = 0;

int Squares[8][8]; //chessboard max size

void goTour(); 

int numberofOperations;
ofstream outputFile; 

int knightPos; //position of the knight 

bool safe;


int main()
{
   outputFile << "\n test version: 234" << endl;
   //choose a chessboard size:
   int brdSizes[5] = {2, 3, 4, 6, 8};
   cout << ("\n please enter the size of chessboard. \n available sizes: 2, 3, 4, 6, 8 \n");
   cin >> usrSize; 
   cout << "you entered: " << usrSize; 
   
   for (int i = 0; i <= 5; i++)
   {
      if (usrSize == brdSizes[i]) {
         brdSize = usrSize * usrSize;
         cout << "\nboardsize = " << brdSize;
         break;
      }
      if (i == 5)
      {
         cout << "\n invalid board size. please try again.";
         return 0;
      }
    }
    
    cout << "\nnow please enter the position of the Knight :";
    cin >> n[0] >> n[1];
    cout << "\nyou entered: " << n[0] << " " << n[1];
    
    //create the chessboard; 
    outputFile.open("knight's tour.txt"); // display the knight's moves for every square. 
    
    outputFile << "\n board initalized...\n"; 
    
    for (int x = 0; x < usrSize; x++){
      for (int y = 0; y < usrSize; y++) {
         Squares[x][y] = -1; 
         outputFile << Squares[x][y] << setw(2);
        }
      
      outputFile << "\n";  
      }
      
    cout << "\ninitial position of the knight: " << n[0] << " " << n[1];
    
    Squares[(n[0])][(n[1])] = 0; //initial position of the knight. 
    
       //begin the knight's tour. 
   
   /*    
  if( remove( "knight's tour.txt" ) != 0 ){
    perror( "error deleting file; no old file found. " );
    }
  else
    puts( "\nolder file successfully deleted" );
  */
  
   
    goTour(); 
    outputFile.close(); 
    
    char waitbeforeClosing;
    cout << "\nenter any char to exit...";
    cin >> waitbeforeClosing; 
    
    return 0;
} //main()

void goTour()
{
   cout << "\nknight is running...";
   //once bound is reached; print all values...
   
   if (steps == brdSize)
   {
      outputFile << "\n";
      for (int x = 0; x < usrSize; x++){
         for(int y = 0; y < usrSize; y++)
              outputFile << Squares[x][y] << setw(2);
               
       outputFile << "\n";
      }
   } //steps == brdSize
   
   //ensure that the Knight can move...
   if (steps <= brdSize)
   {
   
      for (int scan = 0; scan < 8; scan++){ //traverse the move list. 
          outputFile << "\nscan: " << scan << endl;
          scanHorizon = n[0] + horizontal[scan];
          scanVertical = n[1] + vertical[scan];
          outputFile << Squares[scanHorizon][scanVertical] << "\n";
          knightPos = Squares[scanHorizon][scanVertical];
          outputFile<< "\n knightPos: " << knightPos << endl;
          
           outputFile << "\n scanHorizon: " << scanHorizon << " scanVertical: " << scanVertical << endl;
          //is it safe to move?
          
          if (((scanHorizon >= 0) && (scanHorizon < usrSize) && (scanVertical >= 0) && (scanVertical < usrSize) && (knightPos == -1)) == true)
          {
            safe = true; 
            if (safe == true)
               outputFile << " safe to move.\n";
          }
          else {
            safe = false;
            outputFile << " not safe to move.\n";
          }

          if (safe == true)
          {
           
            //outputFile << "\n scanHorizon: " << scanHorizon << " scanVertical: " << scanVertical << endl; 
            steps += 1;
            outputFile << "\n steps: " << steps << endl;
           // cout << "steps = " << steps;
            n[0] = scanHorizon;
            n[1] = scanVertical;
            outputFile << "\n current position of knight: " << n[0] << n[1] << endl;
            Squares[scanVertical][scanHorizon] = steps;
            
            //goTour();
            outputFile << "\n";
            
            for (int x = 0; x < usrSize; x++)
                {
                   for (int y = 0; y < usrSize; y++)
                        outputFile << setw(6) << Squares[x][y];
                  
                   outputFile << "\n";
                }
                      
           }//safe to move. 
           else 
           {
             //  Squares[scanHorizon][scanVertical] = -1; 
               safe = false;
           }
   
      safe = false;
      //outputFile << "safe condition reset: " << safe; 
      } //scan for loop.
   } //steps <= brdsize
    cout << "\n done";
   return;
   
} // goTour();
Last edited on
If your variable is really changing without any explicit statements to change it then it's likely some kind of overflow of another object writing into it. For example, on line 125 above you are accessing Squares at coords that haven't yet been bounds checked. And on line 152 you are using the coords backwards (relative to all the other uses in the program).

Here's a quick rewrite of your code, getting rid of the globals (and the debugging stuff).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;

struct {
    int x, y;
} moves[8] = {{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}};

void doTour(int board[][8], int brdSize, int, int, int); 

int main()
{
    int board[8][8];
    int brdSize = 0;

    do {
        cout << ("Enter the size of chessboard (2 to 8): ");
        cin >> brdSize; 
    } while (brdSize < 2 || brdSize > 8);

    int startX = 0, startY = 0;
    cout << "Enter the position of the Knight: ";
    cin >> startX >> startY;

    for (int x = 0; x < brdSize; x++)
        for (int y = 0; y < brdSize; y++)
            board[x][y] = -1; 

    doTour(board, brdSize, startX, startY, 0);

    return 0;
}

void doTour(int board[][8], int brdSize, int x, int y, int step)
{
    if (step == brdSize * brdSize) {
        for (int x = 0; x < brdSize; x++) {
            for(int y = 0; y < brdSize; y++)
                cout << setw(2) << board[x][y] << ' ';
            cout << '\n';
        }
        exit(0); // Only find first solution
    }

    if (x >= 0 && x < brdSize &&
        y >= 0 && y < brdSize && board[x][y] == -1) {

        board[x][y] = step;

        for (int i = 0; i < 8; i++)
            doTour(board, brdSize, x + moves[i].x, y + moves[i].y, step + 1);

        board[x][y] = -1;
    }
}


It won't be very good at solving 8x8 (or larger) though. For that you'll need to prune the search tree by searching paths with the least branching first.
Last edited on
thank you very much sir.
Topic archived. No new replies allowed.