馬的遍歷問題

最近在複習一些數據結構和經典算法

在寫馬的遍歷問題時遇到了死循環,不知道問題出在哪裏,下面是代碼,請高手指點

//馬的遍歷
bool travelCells(int x,int y,vector<vector<int>>& cellsVV,vector<vector<int>>& passVV)
{
 static int hasPassed = 0;

 cellsVV[x][y] = 1;
 hasPassed++;

 if(64 == hasPassed)
  return true;
 
 int i,j;
 i = x - 1;
 j = y - 2;
 if (i>=0 && j>=0 && cellsVV[i][j] == 0)
  passVV[x*8+y].push_back(i*8+j);
 i = x - 2;
 j = y - 1;
 if (i>=0 && j>=0 && cellsVV[i][j] == 0)
  passVV[x*8+y].push_back(i*8+j);
 i = x - 2;
 j = y + 1;
 if (i>=0 && j<8 && cellsVV[i][j] == 0)
  passVV[x*8+y].push_back(i*8+j);
 i = x - 1;
 j = y + 2;
 if (i>=0 && j<8 && cellsVV[i][j] == 0)
  passVV[x*8+y].push_back(i*8+j);
 i = x + 1;
 j = y + 2;
 if (i<8 && j<8 && cellsVV[i][j] == 0)
  passVV[x*8+y].push_back(i*8+j);
 i = x + 2;
 j = y + 1;
 if (i<8 && j<8 && cellsVV[i][j] == 0)
  passVV[x*8+y].push_back(i*8+j);
 i = x + 2;
 j = y - 1;
 if (i<8 && j>=0 && cellsVV[i][j] == 0)
  passVV[x*8+y].push_back(i*8+j);
 i = x + 1;
 j = y - 2;
 if (i<8 && j>=0 && cellsVV[i][j] == 0)
  passVV[x*8+y].push_back(i*8+j);
 
 while(!passVV[x*8+y].empty())
 {
  int newX = passVV[x*8+y][0]/8;
  int newY = passVV[x*8+y][0]%8;
  bool res = travelCells(newX,newY,cellsVV,passVV);
  if (!res)
  {
   passVV[x*8+y].erase(passVV[x*8+y].begin());
   cellsVV[newX][newY] = 0;
   hasPassed--;
  }
  else
   return true;
 }
 
 return false;
}

//測試函數

void autoTestPass()
{
 vector<vector<int>> cellsVV(8,vector<int>(8));
 vector<vector<int>> passVV(64);
 for (int i=0;i<8;i++)
 {
  for (int j=0;j<8;j++)
  {
   cout<<"起始x:"<<i<<"起始y:"<<j<<endl;
   bool res = travelCells(i,j,cellsVV,passVV);
   if (res)
   {
    vector<vector<int>>::const_iterator tmpIter = passVV.begin();
    while(tmpIter!=passVV.end())
    {
     if (!tmpIter->empty())
     {
      int nPass = *(tmpIter->begin());
      cout<<"x:"<<nPass/8<<" && "<<"y:"<<nPass%8<<endl;
     }
     tmpIter++;
    }
   }
   else
   {
    cout<<"沒有找到遍歷路徑:(/n";
   }
  }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章