在 C++ 中找到從給定的起始字元最長的連續路徑長度


給定一個不同字元的矩陣。從一個字元開始,我們必須透過遍歷所有大於當前字元的字元來找到最長路徑。這些字元是連續的。

從 E 開始。

為了找到最長路徑,我們將使用深度優先搜尋演算法。在 DFS 期間,一些子問題可能會多次出現。為了避免一遍又一遍地計算這些子問題,我們將使用動態規劃方法。

示例

 即時演示

#include<iostream>
#define ROW 3
#define COL 3
using namespace std;
// tool matrices to recur for adjacent cells.
int x[] = {0, 1, 1, -1, 1, 0, -1, -1};
int y[] = {1, 0, 1, 1, -1, -1, 0, -1};
int longestPath[ROW][COL];
char mat[ROW][COL] = {
   {'a','c','d'},
   {'h','b','a'},
   {'i','g','f'}
};
int max(int a, int b){
   return (a>b)?a:b;
}
bool isvalid(int i, int j){
   if (i < 0 || j < 0 || i >= ROW || j >= COL) //when i and j are in range
   return false;
   return true;
}
bool isadjacent(char previous, char current){
   return ((current - previous) == 1); //check current and previous are adjacent or not
}
int findLongestLen(int i, int j, char prev){
   if (!isvalid(i, j) || !isadjacent(prev, mat[i][j]))
      //when already included or not adjacent
      return 0;
   if (longestPath[i][j] != -1)
   return longestPath[i][j]; //subproblems are solved already
   int len = 0; // Initialize result to 0
   for (int k=0; k<8; k++) //find length of the largest path recursively
   len = max(len, 1 + findLongestLen(i + x[k], j + y[k], mat[i][j]));
      return longestPath[i][j] = len; // save the length and return
}
int getLen(char start){
   for(int i = 0; i<ROW; i++)
   for(int j = 0; j<COL; j++)
   longestPath[i][j] = -1; //set all elements to -1
   int len = 0;
   for (int i=0; i<ROW; i++){
      for (int j=0; j<COL; j++){ // check for all possible starting point
         if (mat[i][j] == start) {
            for (int k=0; k<8; k++) //for all eight adjacent cells
               len = max(len, 1 + findLongestLen(i + x[k], j + y[k], start));
            }
         }
   }
   return len;
}
int main() {
   char start;
   cout << "Enter Starting Point (a-i): "; cin >> start;
   cout << "Maximum consecutive path: " << getLen(start);
   return 0;
}

輸出

Enter Starting Point (a-i): e
Maximum consecutive path: 5

更新日期:18-12-2019

116 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始吧
廣告