本文主要是介绍LeetCode 562,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
解法参考:https://www.youtube.com/watch?v=QnAqoK0GHTo
Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal.
/*** 动态规划解法* @param matrix* 01矩阵* [[0,1,1,0],* [0,1,1,0],* [0,0,0,1]]* @return 返回水平、垂直、对角线中最多的1*/public int longestLine(int[][] matrix){if (matrix == null || matrix.length == 0) return 0;int rows = matrix.length, cols = matrix[0].length;int[][][] dp = new int[rows + 1][cols + 2][4]; //动态规划 行+1 列+2 4个方向(水平、垂直、2对角)int res = 0;for (int i = 0; i < rows; i++){for (int j = 0; j < cols; j++){if (matrix[i][j] == 1){dp[i+1][j+1][0] = dp[i+1][j][0] + 1;res = Math.max(res, dp[i+1][j+1][0]);dp[i+1][j+1][1] = dp[i][j+1][1] + 1;res = Math.max(res, dp[i][j+1][1]);dp[i+1][j+1][2] = dp[i][j][2] + 1;res = Math.max(res, dp[i][j][2]);dp[i+1][j+1][3] = dp[i][j+2][3] + 1;res = Math.max(res, dp[i][j+2][3]);}}}return res;}
这篇关于LeetCode 562的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!