LeetCode 329. 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].
思路:
bfs更新。
AC代码:
int path[4][2] = { {-1, 0}, {1, 0},{0, -1},{0, 1} }; class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix) { int n = matrix.size(); if(n == 0) return 0; int m = matrix[0].size(); vector<int> temp(m, 0); vector< vector<int>> dp(n, temp); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(dp[i][j] == 0) { queue<int>q; q.push(i*m+j); dp[i][j] = 1; while(!q.empty()) { int k = q.front(); q.pop(); int x = k/m, y = k%m; for(int w = 0; w<4; w++) { int xx = x+path[w][0]; int yy = y+path[w][1]; if(xx>=0&&xx<n&&yy>=0&&yy<m) { if(matrix[xx][yy] > matrix[x][y] && dp[xx][yy]<dp[x][y]+1) { dp[xx][yy] = dp[x][y]+1; q.push(xx*m+yy); } } } } } } } int ans = 0; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) ans = max(ans, dp[i][j]); } return ans; } };

浙公网安备 33010602011771号