Robot Matrix


https://docs.google.com/document/d/1qxA2wps0IhVRWULulQ55W4SGPMu2AE5MkBB37h8Dr58/edit#

3. 机器人左上到右上(高频 9次)

LC类似题目: LC 62 Unique Paths 和 LC 63 Unique Paths II
给定一个矩形的宽和长,求所有可能的路径数量
http://massivealgorithms.blogspot.com/2014/06/leetcode-62-unique-paths.html
Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
Rules:          
1. 从左上角走到右上角   
2. 机器人只能走右上,右和右下;j
思路:
  1. 按照列dp, dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1] + dp[i + 1][j - 1], 注意i-1,i+1需要存在

followup1: 优化空间复杂度至 O(n)     

思路:只保留上一列的空间,用两个数组滚动dp      
参考代码      
provider: null   
public int uniquePaths(int rows, int cols) {   
int[] dp = new int[rows];   
int[] tmp = new int[rows];   
dp[0] = 1;                                          
for(int j = 1 ; j  < cols ; j++) {
for(int i = 0 ; i < rows ; i++) {
int val1 = i - 1 >= 0 ? dp[i - 1] : 0;
int val2 = dp[i];
int val3 = i + 1 < rows ? dp[i + 1] : 0;
tmp[i] = val1 + val2 + val3;
}
System.arraycopy(tmp, 0, dp, 0, tmp.length);
}
return dp[0];
}
C++ version:
(Provider: Anonym)
int uniquePath(const vector<vector<int>>& grid) {
   if(grid.empty() or grid[0].empty()) return 0;
   int rows = grid.size(), cols = grid[0].size();
   vector<int> pre(rows, 0), cur(rows, 0);
   pre[0] = 1;
   for(int j = 1 ; j < cols; j++) {//roll on by column
       for(int i = 0; i < rows; i++) {
       //simply means: cur[i]=pre[i]+pre[i-1]+pre[i+1]
       cur[i] = pre[i] + (i-1>=0? pre[i-1] : 0) + (i+1<rows? pre[i+1]: 0) ;
       }
       cur.swap(pre);
   }
   return pre[0];
}

滚动数组用位操作写起来会比较清晰,而且可以避免额外的copy
int uniquePath(const vector<vector<int>>& grid) {
   if(grid.empty() || grid[0].empty()) return 0;
   int rows = grid.size(), cols = grid[0].size();
   vector<vector<int>> dp(2,  vector<int>(rows, 0));
   pre[0][0] = 1;//(ze yang)应该是dp吧,不过改了还是不对
   int e = 1;
   for(int j = 1 ; j < cols; j++, e ^= 1) {//roll on by column
       for(int i = 0; i < rows; i++) {
       dp[e][i] = dp[e ^ 1][i] + (i-1>=0? dp[e ^ 1][i - 1] : 0) + (i+1<rows? dp[e ^ 1][i + 1]: 0) ;
       }
   }
   return dp[e ^ 1][0];
}

followup2: 给定矩形里的三个点,判断是否存在遍历这三个点的路径

思路:
假设三个点坐标为(x1, y1) (x2, y2) (x3, y3)
1:从(0,0)出发,如果后一个点在前一个点展开的扇形区域内,则可以被达到
2:先对三个点按照纵坐标y排序,如果一个y上有一个以上的点,则返回false
请问这是是不是应该是如果x上有一样的点返回false啊,方向如果是→ ↗ ↘的话,x应该是单调增的 y可以不是单调吧,还是我理解的题目不太对,感谢 (Editor: 这里的Y是列坐标,即j,不是坐标系中的纵坐标)
(这个没有看太懂从(0 0)怎么走? 是不是不只是向右 和 向下)
(Editor:这个只是follow up,题目还是原题,只能往右边,右上和右下走)
3:对于(xi, yi),得到前一个点在该列的可达范围
              len = yi - y(i-1)
              upper = x(i-1) - len
              lower = x(i-1) + len
如果[xi]在这个范围内 (lower <= xi <= upper),则可达
参考代码
provider: null  
public boolean canReach(int[][] points) {
List<int[]> list = new ArrayList<>();
list.add(new int[] {0, 0});
for(int[] point : points) list.add(point);
Collections.sort(list, (a, b) -> {
return a[1] - b[1];
});
for(int i = 1 ; i < list.size() ; i++) {
int[] curr = list.get(i);
int[] prev = list.get(i-1);
if(curr[1] == prev[1]) return false;// 此处的判断不够严谨;还有一种情况是,两个点在同一列上,但这两个点其实是同一个点,则我们不应该直接zhi'jiefalse
int len = curr[1] - prev[1];
int upper = prev[0] - len;
int lower = prev[0] + len;
if(curr[0] <= lower && curr[0] >= upper) continue;
else return false;
}
return true;
}

Questions

个人认为,上述思路存在逻辑问题。

假设p1, p2两个点,如果p1可以到p2,可以推出p2在p1的后置扇形区域。但是,p2在p1的后置扇形区域,并不能推出说


followup3: 给定矩形里的三个点,找到遍历这三个点的所有路径数量

思路:
1:还是按照follow up 1的思路用滚动数组dp,但是如果当前列有需要到达的点时,只对该点进行dp,其他格子全部置零,表示我们只care这一列上经过目标点的路径
2:如果一列上有多个需要达到的点,直接返回0;
参考代码
provider: null
public int uniquePaths(int rows, int cols, int[][] points) {
int[] dp = new int[rows];
int[] tmp = new int[rows];
Map<Integer, Integer> map = new HashMap<>();
for(int[] point : points) {
if(map.containsKey(point[1])) {
return 0;
} else {
map.put(point[1], point[0]);
}
}
int res = 0;
dp[0] = 1;
for(int j = 1 ; j  < cols ; j++) {
for(int i = 0 ; i < rows ; i++) {
int val1 = i - 1 >= 0 ? dp[i - 1] : 0;
int val2 = dp[i];
int val3 = i + 1 < rows ? dp[i + 1] : 0;
tmp[i] = val1 + val2 + val3;
}
System.arraycopy(tmp, 0, dp, 0, tmp.length);
if(map.containsKey(j)) {
int row = map.get(j);
for(int i = 0 ; i < rows ; i++) {
if(i != row) dp[i] = 0;
else res = dp[i];
}
}
}
return res;
}


followup4: 给定一个下界

(x == H),找到能经过给定下界的所有从左上到右上的路径数量 (x >= H)

思路:
1:先dp一遍,得到所有到右上的路径数量
2:然后在 0<=x<=H, 0<=y<=cols 这个小矩形中再DP一遍得到不经过下界的所有路径数量
3:两个结果相减得到最终路径数量
Code
重用follow up 1的代码
public int uniquePaths(int rows, int cols, int H) {
return uniquePaths(rows, cols) - uniquePaths(H, cols);
}


followup5: 起点和终点改成从左上到左下,每一步只能 ↓↘↙,求所有可能的路径数量

参考代码:按照 行 dp,其他地方不变
Provider: null
public int uniquePaths(int rows, int cols) {
int[] dp = new int[cols];
int[] tmp = new int[cols];
dp[0] = 1;
for(int i = 1 ; i  < rows ; i++) {
for(int j = 0 ; j < cols ; j++) {
int val1 = j - 1 >= 0 ? dp[j - 1] : 0;
int val2 = dp[j];
int val3 = j + 1 < cols ? dp[j + 1] : 0;
tmp[i] = val1 + val2 + val3;
}
System.arraycopy(tmp, 0, dp, 0, tmp.length);
}
return dp[0];
}

补充一个该题目变种:

Given a N*N matrix with random amount of money in each cell, you start from top-left, and can only move from left to right, or top to bottom one step at a time until you hit the bottom right cell. Find the path with max amount of money on its way.
Sample data:
start
|
v
5,   15,20,  ...
10, 15,  5, ...
30,  5, 5,    ...

                ^end here.
思路:LC 64 最小路径和,思路差不多,只是求和变成求相加后的最大值

Follow up 1:要求重建从end 到 start的路径

思路:用另一个额外数组记录每一步选择的parent,dp结束后,从end依次访问它的parent重建路径

Follow up 2: 现在要求空间复杂度为O(1),dp且重建路径

空间复杂度不算返回路径时需要的空间
思路:直接修改原数组,而且带上符号,负号表示从当前cell的左边过来,正号表示从当前cell的上边过来,dp结束后从end 依次访问它的parent重建路径  

数组全是零(或者左上角一块是零)的话就没有办法通过正负号判断来的方向了吧,这样在重构path的时候可能会index out of bound,觉得还是check左边和右边哪个更大就是从那边来的更好,然后注意第一行和第一列的特殊情况,这样不会出问题
(这个方法是面试官给的hint提示的,原数组应该都是正整数。如果全是0,用正负号表示也可以特殊处理一下第一行和第一列的情况即可,即遇到i为0时候总是往左走,j为0的时候总是往上走。)

参考代码
Provider: null
public List<List<Integer>> maxMoney(int[][] moneys) {
// assume: moneys is not null, width and length are equal
int n = moneys.length;
if (n == 0)
return new ArrayList<>();
// base case
for (int j = 1; j < n; j++) {
moneys[0][j] = -(Math.abs(moneys[0][j-1]) + moneys[0][j]);
}
for (int i = 1 ; i < n ; i++) {
moneys[i][0] = moneys[i-1][0] + moneys[i][0];
}
for(int i = 1; i < n ; i++) {
for(int j = 1; j < n ; j++) {
int top = Math.abs(moneys[i-1][j]) + moneys[i][j];
int left = Math.abs(moneys[i][j-1]) + moneys[i][j];
if(top >= left) moneys[i][j] = top;
else moneys[i][j] = -left;
}
}
System.out.println("Max path sum = " + Math.abs(moneys[n - 1][n - 1]));
List<List<Integer>> path = new ArrayList<>();
int curri = n-1;
int currj = n-1;
while (curri > 0 || currj > 0) {
path.add(Arrays.asList(curri, currj));
if(moneys[curri][currj] < 0) {
currj -= 1;
//这里要check一下currj/curri是否到0,否则indexOutOfBound了
} else {
curri -=1;
}
}
path.add(Arrays.asList(0, 0));
return path;
}

follow up:
补充:若机器人只能走右上,右和右下。请问
1. 有三个点需要遍历
2. 如何判断三个点一个是合理的,即存在遍历三个点的路径
3. 给H,需要向下越过H界
思路:
  1. 用三个点切割矩形,然后每个小块复用之前的方法,最后做乘积 什么叫做用3个点切割矩形哇?就是用起始点到最左点对角线的矩形是第一个矩形,第一点到第二点构成的矩形为第二矩形,以此类推我们就得出三个小矩形,分别计算并乘积
  2. 切割后的矩形高度不能超过宽度,不然没法走到 为什么高度不能超过宽度哇,我觉得可以啊,感觉前面的点的横纵坐标比后面的切割点的横纵坐标小或者等于才可以遍历所有点,跟矩形高度宽度有什么关系呢,不懂 因为如果高度为5,长度为2 从左上角到右下角走不过去 为啥走不过去啊?就是个矩形,往下面走就好了啊,不懂诶,这个跟矩形高度宽度有啥关系。不好意思,看followup补充。题目略有变动我忘记说了
  3. 若给定H,先总的dp走一遍,再不越界走一遍(不越界走一遍是什么意思哇 就是用高度为H 宽度相等的矩形再来一遍,相减即可 给定 h是什么意思哇,是高度的意思么?就是给你横着画一条线,然后从左上到右上的所有路线 必须经过这条线或以下的区域

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts