zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    find the safest road
    杭电1874(畅通工程续)
    Red and Black
    运行和控制 Nginx 命令行参数和信号
    对中文版“Siri”打个招呼吧!
    《星际迷航》语音翻译器成真
    程序员丰厚的待遇能持续多久?
    Nginx 日志分析 AWStats + JAWStats 安装配置
    RHEL 5.4 + Nginx + Mediawiki
    麻省理工科技创业之:Win 8新概念
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5226193.html
Copyright © 2011-2022 走看看