1. 程式人生 > >LeetCode 562. Longest Line of Consecutive One in Matrix(在矩陣中最長的連續1)$

LeetCode 562. Longest Line of Consecutive One in Matrix(在矩陣中最長的連續1)$

find ive col discus hint 分開 arr public 標簽

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.


題目標簽:Array

  這道題目給了我們一個2d array,讓我們找出最長1的長度。這裏可以有四個方向,橫向,縱向,還有兩個不同方向的 斜線。

  一開始想到的是維護一個dp 2d array,如果遍歷2d array的話,對於rows 是從上到下,對於 每一個row 是從左到右。所以每一個cell的累加方向只能有4個可能:

  1. 從左邊的cell 累加;

  2. 從左上方的cell 累加;

  3. 從上方的cell 累加;

  4. 從右上方的cell 累加。

  但是這裏存在一個問題,因為有4個方向的累加,在之後的累加裏,會搞不清楚之前存在的值,是從哪個方向累加來的。所以對於每一個cell,我們要把4個方向分開存放。

  這樣的話,我們可以設一個dp 3d array 在最後一個維度的array裏,存放4種不同方向的累加。

  比如:最後一個維度 array [1, 2, 3, 4] 每一個value 都代表著對應方向的累加。[左邊,左上,上方,右上]。

  有了這樣的結構,在遍歷中,我們就可以累加4個方向的長度,每次遇到M 裏是1的cell, 就把 3d array裏的4個方向值都設為1,再檢查這個cell 的 4個方向,左邊,左上,上方,右上,進行累加。在累加完畢後,更新最大的長度。

Java Solution:

Runtime beats 66.48%

完成日期:10/05/2017

關鍵詞:Array, Dynamic Programming

關鍵點:維護一個3d array,累加4個不同方向的長度

 1 class Solution 
 2 {
 3     public int longestLine(int[][] M) 
 4     {
 5         if(M == null || M.length == 0)
 6             return 0;
 7             
 8         int n = M.length;
 9         int m = M[0].length;
10         
11         int[][][] arr = new int[n][m][4];
12         int longestLine = 0;
13         
14         for(int i=0; i<n; i++)
15         {
16             for(int j=0; j<m; j++)
17             {
18                 if(M[i][j] == 0) // skip 0
19                     continue;
20                 
21                 // if find a 1, put 1 into 4 cells since this number is 1
22                 for(int k=0; k<4; k++)
23                     arr[i][j][k] = 1;
24                 // then, add its 4 direction left, up-left, up, up-right value into this 4 cells
25                 if(j-1 >= 0) 
26                     arr[i][j][0] += arr[i][j-1][0];     // horizontal
27                 if(j-1 >= 0 && i-1 >= 0)
28                     arr[i][j][1] += arr[i-1][j-1][1];     // diagonal
29                 if(i-1 >= 0)
30                     arr[i][j][2] += arr[i-1][j][2];        // vertical 
31                 if(j+1 < m && i-1 >= 0)
32                     arr[i][j][3] += arr[i-1][j+1][3];     // anti-diagonal
33                 
34                 int temp = Math.max(Math.max(arr[i][j][0], arr[i][j][1]), Math.max(arr[i][j][2], arr[i][j][3]));
35                 longestLine = Math.max(longestLine, temp);
36             }
37         }
38         
39         return longestLine;
40     }
41 }

參考資料:

https://discuss.leetcode.com/topic/87197/java-o-nm-time-dp-solution

LeetCode 題目列表 - LeetCode Questions List

LeetCode 562. Longest Line of Consecutive One in Matrix(在矩陣中最長的連續1)$