码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Increasing Path in a Matrix

时间:2016-02-29 01:55:30      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Longest Increasing Path in a Matrix

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5226193.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!