How to find the longest sequence in a 2d array?












0














Given a 2d grid, with the below constraints, I want to find the longest sub-sequence :




  1. allowed to move up, right, left, down, diagonally

  2. difference between the current value and the next value should be greater than or equal to 3 (i.e absolute difference).

  3. visited cells should not be repeated

  4. grid could be maximum 10 x 10

  5. not allowed to do 4 -> 9 in the below example


Example:



824
061
379


The length of the longest path for the above input is 8, with the sequence 9,1,6,2,8,0,7,3



I tired to approach using multiple for loops, but it would be highly inefficient. I want to know how do I approach using Dynamic Programming. Any help would be appreciated.










share|improve this question
























  • if you want to use dynamic programming you need to define a recurrence relation with base case first. that shouldn't be very hard since you already got a feeling that the same subproblems are called multiple times
    – mangusta
    Nov 21 at 3:46










  • Pham, I've edited the question. It's actually greater than or equal to 3.
    – Ramesh
    Nov 21 at 3:56






  • 2




    This looks like a variation of the en.wikipedia.org/wiki/Longest_path_problem to me. So there might be no efficient solution.
    – SaiBot
    Nov 21 at 7:05










  • Why not do a depth first search instead of dynamic programming?
    – vivek_23
    Nov 21 at 7:11










  • apparently I think it cannot be solved by means of dynamic programming, because all subproblems are distinct from each other. for example, we would like to find sequences starting with 2 and 7. at first glance it seems that going one step down for 2 and one step up for 7 will call the same subproblem i.e. start with 6, but it is actually not the same subproblem because if we go from 2, then 2 is visited so we can't pick 2 anymore, and if we go from 7 then 7 is visited and we can't pick 7 anymore
    – mangusta
    Nov 21 at 7:15
















0














Given a 2d grid, with the below constraints, I want to find the longest sub-sequence :




  1. allowed to move up, right, left, down, diagonally

  2. difference between the current value and the next value should be greater than or equal to 3 (i.e absolute difference).

  3. visited cells should not be repeated

  4. grid could be maximum 10 x 10

  5. not allowed to do 4 -> 9 in the below example


Example:



824
061
379


The length of the longest path for the above input is 8, with the sequence 9,1,6,2,8,0,7,3



I tired to approach using multiple for loops, but it would be highly inefficient. I want to know how do I approach using Dynamic Programming. Any help would be appreciated.










share|improve this question
























  • if you want to use dynamic programming you need to define a recurrence relation with base case first. that shouldn't be very hard since you already got a feeling that the same subproblems are called multiple times
    – mangusta
    Nov 21 at 3:46










  • Pham, I've edited the question. It's actually greater than or equal to 3.
    – Ramesh
    Nov 21 at 3:56






  • 2




    This looks like a variation of the en.wikipedia.org/wiki/Longest_path_problem to me. So there might be no efficient solution.
    – SaiBot
    Nov 21 at 7:05










  • Why not do a depth first search instead of dynamic programming?
    – vivek_23
    Nov 21 at 7:11










  • apparently I think it cannot be solved by means of dynamic programming, because all subproblems are distinct from each other. for example, we would like to find sequences starting with 2 and 7. at first glance it seems that going one step down for 2 and one step up for 7 will call the same subproblem i.e. start with 6, but it is actually not the same subproblem because if we go from 2, then 2 is visited so we can't pick 2 anymore, and if we go from 7 then 7 is visited and we can't pick 7 anymore
    – mangusta
    Nov 21 at 7:15














0












0








0







Given a 2d grid, with the below constraints, I want to find the longest sub-sequence :




  1. allowed to move up, right, left, down, diagonally

  2. difference between the current value and the next value should be greater than or equal to 3 (i.e absolute difference).

  3. visited cells should not be repeated

  4. grid could be maximum 10 x 10

  5. not allowed to do 4 -> 9 in the below example


Example:



824
061
379


The length of the longest path for the above input is 8, with the sequence 9,1,6,2,8,0,7,3



I tired to approach using multiple for loops, but it would be highly inefficient. I want to know how do I approach using Dynamic Programming. Any help would be appreciated.










share|improve this question















Given a 2d grid, with the below constraints, I want to find the longest sub-sequence :




  1. allowed to move up, right, left, down, diagonally

  2. difference between the current value and the next value should be greater than or equal to 3 (i.e absolute difference).

  3. visited cells should not be repeated

  4. grid could be maximum 10 x 10

  5. not allowed to do 4 -> 9 in the below example


Example:



824
061
379


The length of the longest path for the above input is 8, with the sequence 9,1,6,2,8,0,7,3



I tired to approach using multiple for loops, but it would be highly inefficient. I want to know how do I approach using Dynamic Programming. Any help would be appreciated.







algorithm recursion data-structures dynamic-programming






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 at 3:53

























asked Nov 21 at 3:30









Ramesh

11




11












  • if you want to use dynamic programming you need to define a recurrence relation with base case first. that shouldn't be very hard since you already got a feeling that the same subproblems are called multiple times
    – mangusta
    Nov 21 at 3:46










  • Pham, I've edited the question. It's actually greater than or equal to 3.
    – Ramesh
    Nov 21 at 3:56






  • 2




    This looks like a variation of the en.wikipedia.org/wiki/Longest_path_problem to me. So there might be no efficient solution.
    – SaiBot
    Nov 21 at 7:05










  • Why not do a depth first search instead of dynamic programming?
    – vivek_23
    Nov 21 at 7:11










  • apparently I think it cannot be solved by means of dynamic programming, because all subproblems are distinct from each other. for example, we would like to find sequences starting with 2 and 7. at first glance it seems that going one step down for 2 and one step up for 7 will call the same subproblem i.e. start with 6, but it is actually not the same subproblem because if we go from 2, then 2 is visited so we can't pick 2 anymore, and if we go from 7 then 7 is visited and we can't pick 7 anymore
    – mangusta
    Nov 21 at 7:15


















  • if you want to use dynamic programming you need to define a recurrence relation with base case first. that shouldn't be very hard since you already got a feeling that the same subproblems are called multiple times
    – mangusta
    Nov 21 at 3:46










  • Pham, I've edited the question. It's actually greater than or equal to 3.
    – Ramesh
    Nov 21 at 3:56






  • 2




    This looks like a variation of the en.wikipedia.org/wiki/Longest_path_problem to me. So there might be no efficient solution.
    – SaiBot
    Nov 21 at 7:05










  • Why not do a depth first search instead of dynamic programming?
    – vivek_23
    Nov 21 at 7:11










  • apparently I think it cannot be solved by means of dynamic programming, because all subproblems are distinct from each other. for example, we would like to find sequences starting with 2 and 7. at first glance it seems that going one step down for 2 and one step up for 7 will call the same subproblem i.e. start with 6, but it is actually not the same subproblem because if we go from 2, then 2 is visited so we can't pick 2 anymore, and if we go from 7 then 7 is visited and we can't pick 7 anymore
    – mangusta
    Nov 21 at 7:15
















if you want to use dynamic programming you need to define a recurrence relation with base case first. that shouldn't be very hard since you already got a feeling that the same subproblems are called multiple times
– mangusta
Nov 21 at 3:46




if you want to use dynamic programming you need to define a recurrence relation with base case first. that shouldn't be very hard since you already got a feeling that the same subproblems are called multiple times
– mangusta
Nov 21 at 3:46












Pham, I've edited the question. It's actually greater than or equal to 3.
– Ramesh
Nov 21 at 3:56




Pham, I've edited the question. It's actually greater than or equal to 3.
– Ramesh
Nov 21 at 3:56




2




2




This looks like a variation of the en.wikipedia.org/wiki/Longest_path_problem to me. So there might be no efficient solution.
– SaiBot
Nov 21 at 7:05




This looks like a variation of the en.wikipedia.org/wiki/Longest_path_problem to me. So there might be no efficient solution.
– SaiBot
Nov 21 at 7:05












Why not do a depth first search instead of dynamic programming?
– vivek_23
Nov 21 at 7:11




Why not do a depth first search instead of dynamic programming?
– vivek_23
Nov 21 at 7:11












apparently I think it cannot be solved by means of dynamic programming, because all subproblems are distinct from each other. for example, we would like to find sequences starting with 2 and 7. at first glance it seems that going one step down for 2 and one step up for 7 will call the same subproblem i.e. start with 6, but it is actually not the same subproblem because if we go from 2, then 2 is visited so we can't pick 2 anymore, and if we go from 7 then 7 is visited and we can't pick 7 anymore
– mangusta
Nov 21 at 7:15




apparently I think it cannot be solved by means of dynamic programming, because all subproblems are distinct from each other. for example, we would like to find sequences starting with 2 and 7. at first glance it seems that going one step down for 2 and one step up for 7 will call the same subproblem i.e. start with 6, but it is actually not the same subproblem because if we go from 2, then 2 is visited so we can't pick 2 anymore, and if we go from 7 then 7 is visited and we can't pick 7 anymore
– mangusta
Nov 21 at 7:15












2 Answers
2






active

oldest

votes


















0














Just run bfs (Breadth-first search) from every possible source in the grid by following the constraints. For example, in your given sample input the number of possible source is 9. Then, save the paths in some suitable data structure. After saving the paths, check which path is longest and that's your answer.






share|improve this answer





























    0














    I could find the longest increasing sub-sequence. Can someone suggest, how do I accomodate the condition "difference between the current value and the next value should be greater than or equal to 3" ?. The code below takes care of just an increasing sequence.



    public class Test {



    public static void main(String args) {

    int matrix = {{1,2,3}, {2,4,2}, { 5,6,7}};
    System.out.println(new Test().longestIncreasingPaths(matrix));

    }

    public int longestIncreasingPaths(int matrix) {

    if (matrix == null || matrix.length < 1 || matrix[0].length < 1)
    return 0;

    int max = 0, n = matrix.length, m = matrix[0].length;

    int cache = new int[n][m];

    for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
    max = Math.max(dfs(matrix, Integer.MIN_VALUE, i, j, n, m, cache), max);
    }
    }
    return max;
    }

    int dfs(int matrix, int min, int i, int j, int n, int m, int cache) {

    if (i < 0 || j < 0 || i >= n || j >= m)
    return 0;

    if (matrix[i][j] <= min)
    return 0;

    if (cache[i][j] != 0)
    return cache[i][j];

    min = matrix[i][j];

    int a = dfs(matrix, min, i - 1, j, n, m, cache) + 1;
    int b = dfs(matrix, min, i + 1, j, n, m, cache) + 1;
    int c = dfs(matrix, min, i, j - 1, n, m, cache) + 1;
    int d = dfs(matrix, min, i, j + 1, n, m, cache) + 1;
    int e = dfs(matrix, min, i+1, j + 1, n, m, cache) + 1;
    int f = dfs(matrix, min, i - 1, j - 1, n, m, cache) + 1;
    int g = dfs(matrix, min, i + 1, j - 1, n, m, cache) + 1;
    int h = dfs(matrix, min, i - 1, j + 1, n, m, cache) + 1;

    int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, Math.max(e, Math.max(f, Math.max(g,h)))))));
    cache[i][j] = max;

    return max;
    }


    }






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53404864%2fhow-to-find-the-longest-sequence-in-a-2d-array%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Just run bfs (Breadth-first search) from every possible source in the grid by following the constraints. For example, in your given sample input the number of possible source is 9. Then, save the paths in some suitable data structure. After saving the paths, check which path is longest and that's your answer.






      share|improve this answer


























        0














        Just run bfs (Breadth-first search) from every possible source in the grid by following the constraints. For example, in your given sample input the number of possible source is 9. Then, save the paths in some suitable data structure. After saving the paths, check which path is longest and that's your answer.






        share|improve this answer
























          0












          0








          0






          Just run bfs (Breadth-first search) from every possible source in the grid by following the constraints. For example, in your given sample input the number of possible source is 9. Then, save the paths in some suitable data structure. After saving the paths, check which path is longest and that's your answer.






          share|improve this answer












          Just run bfs (Breadth-first search) from every possible source in the grid by following the constraints. For example, in your given sample input the number of possible source is 9. Then, save the paths in some suitable data structure. After saving the paths, check which path is longest and that's your answer.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 at 13:39









          Golam Rahman Tushar

          666




          666

























              0














              I could find the longest increasing sub-sequence. Can someone suggest, how do I accomodate the condition "difference between the current value and the next value should be greater than or equal to 3" ?. The code below takes care of just an increasing sequence.



              public class Test {



              public static void main(String args) {

              int matrix = {{1,2,3}, {2,4,2}, { 5,6,7}};
              System.out.println(new Test().longestIncreasingPaths(matrix));

              }

              public int longestIncreasingPaths(int matrix) {

              if (matrix == null || matrix.length < 1 || matrix[0].length < 1)
              return 0;

              int max = 0, n = matrix.length, m = matrix[0].length;

              int cache = new int[n][m];

              for (int i = 0; i < n; i++) {
              for (int j = 0; j < m; j++) {
              max = Math.max(dfs(matrix, Integer.MIN_VALUE, i, j, n, m, cache), max);
              }
              }
              return max;
              }

              int dfs(int matrix, int min, int i, int j, int n, int m, int cache) {

              if (i < 0 || j < 0 || i >= n || j >= m)
              return 0;

              if (matrix[i][j] <= min)
              return 0;

              if (cache[i][j] != 0)
              return cache[i][j];

              min = matrix[i][j];

              int a = dfs(matrix, min, i - 1, j, n, m, cache) + 1;
              int b = dfs(matrix, min, i + 1, j, n, m, cache) + 1;
              int c = dfs(matrix, min, i, j - 1, n, m, cache) + 1;
              int d = dfs(matrix, min, i, j + 1, n, m, cache) + 1;
              int e = dfs(matrix, min, i+1, j + 1, n, m, cache) + 1;
              int f = dfs(matrix, min, i - 1, j - 1, n, m, cache) + 1;
              int g = dfs(matrix, min, i + 1, j - 1, n, m, cache) + 1;
              int h = dfs(matrix, min, i - 1, j + 1, n, m, cache) + 1;

              int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, Math.max(e, Math.max(f, Math.max(g,h)))))));
              cache[i][j] = max;

              return max;
              }


              }






              share|improve this answer


























                0














                I could find the longest increasing sub-sequence. Can someone suggest, how do I accomodate the condition "difference between the current value and the next value should be greater than or equal to 3" ?. The code below takes care of just an increasing sequence.



                public class Test {



                public static void main(String args) {

                int matrix = {{1,2,3}, {2,4,2}, { 5,6,7}};
                System.out.println(new Test().longestIncreasingPaths(matrix));

                }

                public int longestIncreasingPaths(int matrix) {

                if (matrix == null || matrix.length < 1 || matrix[0].length < 1)
                return 0;

                int max = 0, n = matrix.length, m = matrix[0].length;

                int cache = new int[n][m];

                for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                max = Math.max(dfs(matrix, Integer.MIN_VALUE, i, j, n, m, cache), max);
                }
                }
                return max;
                }

                int dfs(int matrix, int min, int i, int j, int n, int m, int cache) {

                if (i < 0 || j < 0 || i >= n || j >= m)
                return 0;

                if (matrix[i][j] <= min)
                return 0;

                if (cache[i][j] != 0)
                return cache[i][j];

                min = matrix[i][j];

                int a = dfs(matrix, min, i - 1, j, n, m, cache) + 1;
                int b = dfs(matrix, min, i + 1, j, n, m, cache) + 1;
                int c = dfs(matrix, min, i, j - 1, n, m, cache) + 1;
                int d = dfs(matrix, min, i, j + 1, n, m, cache) + 1;
                int e = dfs(matrix, min, i+1, j + 1, n, m, cache) + 1;
                int f = dfs(matrix, min, i - 1, j - 1, n, m, cache) + 1;
                int g = dfs(matrix, min, i + 1, j - 1, n, m, cache) + 1;
                int h = dfs(matrix, min, i - 1, j + 1, n, m, cache) + 1;

                int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, Math.max(e, Math.max(f, Math.max(g,h)))))));
                cache[i][j] = max;

                return max;
                }


                }






                share|improve this answer
























                  0












                  0








                  0






                  I could find the longest increasing sub-sequence. Can someone suggest, how do I accomodate the condition "difference between the current value and the next value should be greater than or equal to 3" ?. The code below takes care of just an increasing sequence.



                  public class Test {



                  public static void main(String args) {

                  int matrix = {{1,2,3}, {2,4,2}, { 5,6,7}};
                  System.out.println(new Test().longestIncreasingPaths(matrix));

                  }

                  public int longestIncreasingPaths(int matrix) {

                  if (matrix == null || matrix.length < 1 || matrix[0].length < 1)
                  return 0;

                  int max = 0, n = matrix.length, m = matrix[0].length;

                  int cache = new int[n][m];

                  for (int i = 0; i < n; i++) {
                  for (int j = 0; j < m; j++) {
                  max = Math.max(dfs(matrix, Integer.MIN_VALUE, i, j, n, m, cache), max);
                  }
                  }
                  return max;
                  }

                  int dfs(int matrix, int min, int i, int j, int n, int m, int cache) {

                  if (i < 0 || j < 0 || i >= n || j >= m)
                  return 0;

                  if (matrix[i][j] <= min)
                  return 0;

                  if (cache[i][j] != 0)
                  return cache[i][j];

                  min = matrix[i][j];

                  int a = dfs(matrix, min, i - 1, j, n, m, cache) + 1;
                  int b = dfs(matrix, min, i + 1, j, n, m, cache) + 1;
                  int c = dfs(matrix, min, i, j - 1, n, m, cache) + 1;
                  int d = dfs(matrix, min, i, j + 1, n, m, cache) + 1;
                  int e = dfs(matrix, min, i+1, j + 1, n, m, cache) + 1;
                  int f = dfs(matrix, min, i - 1, j - 1, n, m, cache) + 1;
                  int g = dfs(matrix, min, i + 1, j - 1, n, m, cache) + 1;
                  int h = dfs(matrix, min, i - 1, j + 1, n, m, cache) + 1;

                  int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, Math.max(e, Math.max(f, Math.max(g,h)))))));
                  cache[i][j] = max;

                  return max;
                  }


                  }






                  share|improve this answer












                  I could find the longest increasing sub-sequence. Can someone suggest, how do I accomodate the condition "difference between the current value and the next value should be greater than or equal to 3" ?. The code below takes care of just an increasing sequence.



                  public class Test {



                  public static void main(String args) {

                  int matrix = {{1,2,3}, {2,4,2}, { 5,6,7}};
                  System.out.println(new Test().longestIncreasingPaths(matrix));

                  }

                  public int longestIncreasingPaths(int matrix) {

                  if (matrix == null || matrix.length < 1 || matrix[0].length < 1)
                  return 0;

                  int max = 0, n = matrix.length, m = matrix[0].length;

                  int cache = new int[n][m];

                  for (int i = 0; i < n; i++) {
                  for (int j = 0; j < m; j++) {
                  max = Math.max(dfs(matrix, Integer.MIN_VALUE, i, j, n, m, cache), max);
                  }
                  }
                  return max;
                  }

                  int dfs(int matrix, int min, int i, int j, int n, int m, int cache) {

                  if (i < 0 || j < 0 || i >= n || j >= m)
                  return 0;

                  if (matrix[i][j] <= min)
                  return 0;

                  if (cache[i][j] != 0)
                  return cache[i][j];

                  min = matrix[i][j];

                  int a = dfs(matrix, min, i - 1, j, n, m, cache) + 1;
                  int b = dfs(matrix, min, i + 1, j, n, m, cache) + 1;
                  int c = dfs(matrix, min, i, j - 1, n, m, cache) + 1;
                  int d = dfs(matrix, min, i, j + 1, n, m, cache) + 1;
                  int e = dfs(matrix, min, i+1, j + 1, n, m, cache) + 1;
                  int f = dfs(matrix, min, i - 1, j - 1, n, m, cache) + 1;
                  int g = dfs(matrix, min, i + 1, j - 1, n, m, cache) + 1;
                  int h = dfs(matrix, min, i - 1, j + 1, n, m, cache) + 1;

                  int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, Math.max(e, Math.max(f, Math.max(g,h)))))));
                  cache[i][j] = max;

                  return max;
                  }


                  }







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 27 at 3:19









                  Ramesh

                  11




                  11






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53404864%2fhow-to-find-the-longest-sequence-in-a-2d-array%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'