leetcode562- Longest Line of Consecutive One in Matrix- medium
阿新 • • 發佈:2017-12-05
color 一個 mat etc 依賴 ould bound result 連續
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.
Example:
Input: [[0,1,1,0], [0,1,1,0], [0,0,0,1]] Output: 3
Hint: The number of elements in the given matrix will not exceed 10,000.
算法:DP,就可以只遍歷一遍了。dp[4][row][col]做DP。maxL[4]輔助打擂臺。
遍歷各個坐標點,記錄各個坐標位置開始向左向上向左上向右上分別連續出去能延伸多長。記錄下來後打一個擂臺。記錄方法是,
1.如果前一個依賴點出界,就依當前內容物來。
2.如果前一個依賴點在,而且當前內容物是1,那就可以續上前面的。
3.如果前一個依賴點在,但當前內容物是0,那就清空,續不上了。
全遍歷後最後大打擂臺,從四強種決一勝負
實現:
class Solution { public int longestLine(int[][] M) { if (M == null || M.length == 0 || M[0].length == 0) {return 0; } int[][][] dp = new int[4][M.length][M[0].length]; int[] maxL = new int[4]; int[] dx = {0, -1, -1, -1}; int[] dy = {-1, 0, -1, +1}; for (int x = 0; x < M.length; x++) { for (int y = 0; y < M[0].length; y++) { for (inti = 0; i < 4; i++) { int lastX = x + dx[i]; int lastY = y + dy[i]; if (!isInBound(M, lastX, lastY)) { dp[i][x][y] = M[x][y]; } else if (M[x][y] == 0) { dp[i][x][y] = 0; } else { dp[i][x][y] = dp[i][lastX][lastY] + 1; } maxL[i] = Math.max(maxL[i], dp[i][x][y]); } } } int result = 0; for (int i = 0; i < 4; i++) { result = Math.max(result, maxL[i]); } return result; } private boolean isInBound(int[][] M, int x, int y) { return x >= 0 && x < M.length && y >= 0 && y < M[0].length; } }
leetcode562- Longest Line of Consecutive One in Matrix- medium