Data Structure and Algorithms
  • Introduction
  • 面经
    • 亚马逊面经
  • Sorting
    • Quick Sort
    • Merge Sort
    • Heap Sort
  • Palindrome
    • Check String Palindrom
    • Palindrome Partitioning
    • Palindrome Partitioning II
    • Longest Palindromic Substring
    • Valid Palindrome
  • Linked List
    • Remove Duplicates from Sorted List
    • Remove Duplicates from Sorted List II
    • Remove Nth Node From End of List
    • Remove Linked List Elements
    • Remove Duplicates from Unsorted List
    • Remove duplicate Circular Linked list
    • Reverse Linked List
    • Reverse Linked List II
    • Reverse Nodes in k-Group
    • Partition List
    • Insertion Sort List
    • Reorder List
    • Linked List Cycle
    • Rotate List
    • Merge k Sorted Lists
    • Copy List with Random Pointer
    • Nth to Last Node in List
    • Add Two Numbers
    • Add Two Numbers II
    • Palindrome Linked List
  • Binary Search
    • Sqrt(x)
    • Search a 2D Matrix
    • Search a 2D Matrix II
    • Search Insert Position
    • First Position of Target
    • Last Position of Target
    • Count of Smaller Number
    • Search for a Range
    • Search in a Big Sorted Array
    • First Bad Version
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Search in Rotated Sorted Array
    • Search in Rotated Sorted Array II
    • Find Peak Element*
    • Recover Rotated Sorted Array
    • Rotate String
    • Wood Cut
    • Total Occurrence of Target
    • Closest Number in Sorted Array
    • K Closest Number in Sorted Array
    • Maximum Number in Mountain Sequence
    • Search Insert Position *
    • Pow(x, n)
    • Divide Two Integers
  • Graph
    • Clone Graph
    • Topological Sorting
    • Permutations
    • Permutations II
    • Subsets
    • Subsets II
    • Word Ladder
    • Word Ladder II
    • N-Queens
    • N-Queens II
    • Connected Component in Undirected Graph
    • Six Degrees
    • String Permutation II
    • Letter Case Permutation
  • Data Structure
    • Min Stack
    • Implement a Queue by Two Stacks
    • Largest Rectangle in Histogram
    • Max Tree
    • Rehashing
    • LRU Cache
    • Subarray Sum
    • Anagrams
    • Longest Consecutive Sequence
    • Data Stream Median
    • Heapify
    • Ugly Number
    • Ugly Number II
  • Misc
    • PlaceHolder
    • Fibonacci
  • Array and Numbers
    • Merge Sorted Array
    • Merge Two Sorted Arrays
    • Median of two Sorted Arrays
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
    • Best Time to Buy and Sell Stock III
    • Maximum Subarray
    • Maximum Subarray II
    • Maximum Subarray III
    • Minimum Subarray
    • Maximum Subarray Difference
    • Subarray Sum
    • Subarray Sum Closest
    • Two Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum
    • k Sum
    • k Sum II
    • Partition Array
    • Sort Letters by Case
    • Sort Colors
    • Sort Colors II
    • Interleaving Positive and Negative Numbers
    • Spiral Matrix
    • Spiral Matrix II
    • Rotate Image
  • Dynamic Programming I
    • Triangle
    • Minimum Path Sum
    • Unique Paths
    • Unique Paths II
    • Climbing Stairs
    • Jump Game
    • Jump Game II
    • 01 Matrix
    • Longest Line of Consecutive One in Matrix
    • Shortest Path in Binary Matrix
  • Dynamic Programming II
    • Word Break
    • Longest Common Subsequence
    • Longest Common Substring
    • Edit Distance
    • Distinct Subsequences
    • Interleaving String
    • k Sum
  • Binary Tree And Divide Conquer
    • Binary Tree Preorder Traversal*
    • Binary Tree Inorder Traversal*
    • Binary Tree Postorder Traversal*
    • Maximum Depth of Binary Tree
    • Minimum Depth of Binary Tree
    • Balanced Binary Tree
    • Lowest Common Ancestor
    • Binary Tree Maximum Path Sum
    • Binary Tree Maximum Path Sum II
    • Binary Tree Level Order Traversal*
    • Binary Tree Level Order Traversal II
    • Binary Tree Zigzag Level Order Traversal
    • Validate Binary Search Tree
    • Inorder Successor in Binary Search Tree
    • Binary Search Tree Iterator
    • Search Range in Binary Search Tree
    • Insert Node in a Binary Search Tree
    • Remove Node in Binary Search Tree
    • Find the kth largest element in the BST
    • Kth Smallest Element in a BST
    • Serialize and Deserialize Binary Tree*
    • Construct Binary Tree from Preorder and Inorder Traversal
    • Convert Sorted Array to Binary Search Tree
    • Unique Binary Search Trees *
    • Unique Binary Search Trees II *
    • Recover Binary Search Tree
    • Same Tree
    • Symmetric Tree
    • Path Sum*
    • Path Sum II*
    • Flatten Binary Tree to Linked List
    • Populating Next Right Pointers in Each Node
    • Sum Root to Leaf Numbers
    • Binary Tree Right Side View
    • Count Complete Tree Nodes
    • Invert Binary Tree
    • Binary Tree Paths*
    • Subtree of Another Tree
  • A家面试总结
  • Expedia面经收集
  • Python 常用语句
  • lotusflare
  • Microsoft
  • 模板
  • Bing 组面试总结
  • 面试笔记
  • Sliding window
Powered by GitBook
On this page

Was this helpful?

  1. Dynamic Programming I

Longest Line of Consecutive One in Matrix

第一种方法是直接做搜索,LC现在感觉大数据的test case少了,所以繁琐一点也是能过的.

对于每一个点,朝8个方向进行搜索 (其实朝前向的四个方向就可以) 同时将扫过的点记录下来,以便不往回找.

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.

给定01矩阵M,计算矩阵中一条线上连续1的最大长度。一条线可以为横向、纵向、主对角线、反对角线。

提示:

给定矩阵元素个数不超过10,000

class Solution {
public:

    bool isValid(int x, int y, vector<vector<int>>& M, vector<vector<bool>> &visited){
        if(x >= 0 && x < M.size() && y >= 0 && y < M[0].size() && M[x][y] == 1 && !visited[x][y]){
            return true;
        }

        return false;
    }

    int longestLine(vector<vector<int>>& M) {
        if(M.empty() || M[0].empty()){
            return 0;
        }

        int row = M.size(), col = M[0].size();
        vector<vector<bool>> visited(row, vector<bool>(col, false));
        vector<pair<int, int>> directions = {{1, 0}, {0, 1}, {1, 1}, {-1, 1}};
        int max_len = 0;
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(M[i][j] == 0){
                    continue;
                }

                for(auto it : directions){
                    int cur_x = i, cur_y = j, cur_len = 1;
                    while(isValid(cur_x + it.first, cur_y + it.second, M, visited)){
                        cur_x += it.first;
                        cur_y += it.second;
                        cur_len += 1;
                    }

                    max_len = max(max_len, cur_len);
                }
            }
        }

        return max_len;
    }
};

参照网上,第二种方法是dp,这个dp是要建立三维数组,不仅仅是行列这两维,第三维有代表的是连续1的四个方向 (前后,上下,斜,反斜). 做法也很直接.

class Solution {
public:
    int longestLine(vector<vector<int>>& M) {
        if(M.empty() || M[0].empty()) return 0;
        int row = M.size(), col = M[0].size();
        vector<vector<vector<int>>> dp(row+1, vector<vector<int>>(col+1, vector<int>(4, 0)));
        int max_len = 0;
        for(int i=1; i<=row; i++){
            for(int j=1; j<=col; j++){
                if(M[i-1][j-1] == 0) continue;
                dp[i][j][0] = dp[i-1][j][0] + 1;
                dp[i][j][1] = dp[i][j-1][1] + 1;
                dp[i][j][2] = dp[i-1][j-1][2] + 1;
                if(j != col) dp[i][j][3] = dp[i-1][j+1][3] + 1;
                for(int k=0; k<4; k++){
                    max_len = max(max_len, dp[i][j][k]);
                }

            }
        }
        return max_len;
    }
};

## Blog link: https://code.dennyzhang.com/longest-line-of-consecutive-one-in-matrix
## Basic Ideas:
##
##   dp(i, j): 
##        horizontal:    dp(i, j-1)
##        vertical:      dp(i-1, j)
##        diagonal:      dp(i-1, j-1)
##        anti-diagonal: dp(i-1, j+1)
##
## Complexity: Time O(m*n), Space O(m*n)


class Solution:
    def longestLine(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        row_count = len(M)
        if row_count == 0: return 0
        col_count = len(M[0])

        dp = [[[0, 0, 0, 0] for j in range(col_count)] for i in range(row_count)]
        max_count = 0
        # dynamic programming
        for i in range(row_count):
            for j in range(col_count):
                if M[i][j] == 0: continue
                dp[i][j] = [1, 1, 1, 1]
                if j>0: dp[i][j][0] = dp[i][j-1][0] + 1
                if i>0: dp[i][j][1] = dp[i-1][j][1] + 1
                if i>0 and j>0: dp[i][j][2] = dp[i-1][j-1][2] + 1
                if i>0 and j<col_count-1: dp[i][j][3] = dp[i-1][j+1][3] + 1
                max_count = max(max_count, max(dp[i][j]))
        return max_count





class Solution {
    public int longestLine(int[][] M) {
        int n = M.length, max = 0;
        if (n == 0) return max;
        int m = M[0].length;
        int[][][] dp = new int[n][m][4];
        for (int i=0;i<n;i++) 
            for (int j=0;j<m;j++) {
                if (M[i][j] == 0) continue;
                for (int k = 0;k < 4;k++) dp[i][j][k] = 1;
                if (j > 0) dp[i][j][0] += dp[i][j-1][0]; // horizontal line
                if (j > 0 && i > 0) dp[i][j][1] += dp[i-1][j-1][1]; // anti-diagonal line
                if (i > 0) dp[i][j][2] += dp[i-1][j][2]; // vertical line
                if (j < m-1 && i > 0) dp[i][j][3] += dp[i-1][j+1][3]; // diagonal line
                max = Math.max(max, Math.max(dp[i][j][0], dp[i][j][1]));
                max = Math.max(max, Math.max(dp[i][j][2], dp[i][j][3]));
            }
        return max;
    }
}






 public int longestLine(int[][] matrix)
        {
            int m = matrix.Length;
            int n = matrix[0].Length;
            int ans = 0;

            int[][][] F = new int[m][][];
            for(int i = 0; i < m; i++)
            {
                F[i] = new int[n][];
                for(int j = 0; j < n; j++)
                {
                    F[i][j] = new int[4];
                }
            }

            for(int i = 0; i < m; i++)
            {
                for(int j= 0; j < n; j++)
                {
                    if(matrix[i][j] == 0)
                    {
                        continue;
                    }

                    for (int k = 0; k < 4; k++)
                    {
                        F[i][j][k] = 1;
                    }

                    if (j > 0)
                    {
                        F[i][j][0] = F[i][j - 1][0] + 1;
                    }

                    if(i > 0)
                    {
                        F[i][j][1] = F[i - 1][j][1] + 1;
                    }

                    if (i > 0 && j > 0)
                    {
                        F[i][j][2] = F[i - 1][j- 1][2] + 1;
                    }

                    if(i > 0 && j < n - 1)
                    {
                        F[i][j][3] = F[i - 1][j + 1][3] + 1;
                    }

                    for (int k = 0; k < 4; k++)
                    {
                        ans = Math.Max(ans, F[i][j][k]);
                    }

                }
            }

            return ans;

        }
Previous01 MatrixNextShortest Path in Binary Matrix

Last updated 4 years ago

Was this helpful?