给定起始字符的最长连续路径
提供一个由不同字符组成的矩阵。从一个字符开始,我们必须找到通过所有比当前字符大的字符的最长路径。这些字符是相互连的。
要找到最长路径,我们将使用深度优先搜索算法。在进行深度优先搜索时,可能会多次出现一些子问题。为了避免重复计算,我们将使用动态规划方法。
输入和输出
Input: The matrix as shown above. And the starting point. Here the starting point is e. Output: Enter Starting Point (a-i): e Maximum consecutive path: 5
算法
findLongestLen(i, j, prev)
输入: 位置 i 和 j 以及前一个字符。
输出:最长长度。
Begin if (i, j) place is valid or prev and matrix[i,j] are adjacent, then return 0 if longestPath[i, j] is already filled, then return longestPath[i, j] len := 0 for all its nearest 8 rooms k, do len := maximum of len and (1 + findLongestLen(i, x[k], j +y[k], matrix[i, j])) done longestPath[i, j] := len return len End
getLen(start)
输入 - 起始点。
输出 - 最大长度。
Begin for all row r of matrix, do for all column c, of matrix, do if matrix[i, j] = start, then for all adjacent room k, do len := maximum of len and (1 + findLongestLen(i, x[k], j +y[k], matrix[i, j]))) done done done return len End
示例
#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
广告