Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]

 

Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]

 

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

 

Analyse: backtracking. 

Time Limit Exceeded Version.

 1 class Solution {
 2 public:
 3     int longestIncreasingPath(vector<vector<int>>& matrix) {
 4         int result;
 5         if(matrix.empty() || matrix[0].empty()) return result;
 6         
 7         int depth = 0;
 8         vector<vector<bool> > visited(matrix.size(), vector<bool>(matrix[0].size(), false));
 9         for(int i = 0; i < matrix.size(); i++){
10             for(int j = 0; j < matrix[i].size(); j++){
11                 helper(matrix, visited, i, j, result, depth, INT_MIN);
12             }
13         }
14         return result;
15     }
16     
17     void helper(vector<vector<int> >& matrix, vector<vector<bool> > visited, int i, int j, int& result, int depth, int former){
18         if(i >= matrix.size() || i < 0 || j >= matrix[i].size() || j < 0 || matrix[i][j] <= former || visited[i][j])
19             return;
20             
21         visited[i][j] = true;
22         depth++;
23         result = max(result, depth);
24         former = matrix[i][j];
25         helper(matrix, visited, i + 1, j, result, depth, former);
26         helper(matrix, visited, i - 1, j, result, depth, former);
27         helper(matrix, visited, i, j + 1, result, depth, former);
28         helper(matrix, visited, i, j - 1, result, depth, former);
29         visited[i][j] = false;
30     }
31 };
View Code

 

posted @ 2016-02-29 00:53  amazingzoe  阅读(167)  评论(0编辑  收藏  举报