2021-8-15 Out of Boundary Paths

Posted 洛水天iriya

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021-8-15 Out of Boundary Paths相关的知识,希望对你有一定的参考价值。

难度 中等

题目 Leetcode:

Out of Boundary Paths

There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.

Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.

 

题目解析

这题就是用到了bfs,虽然我看好多人用的都是dfs,但感觉我这个也可以吧嘿嘿。

具体的直接看代码吧

 1 class Solution {
 2 public:
 3     int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
 4         queue<int>q;
 5         vector<vector<int>>dp(m,vector<int>(n,0));
 6         int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
 7         q.push(startRow<<8|startColumn);
 8         dp[startRow][startColumn]=1;
 9         int ans=0;
10         int mod=1e9+7;
11         while(maxMove--)
12         {
13             int s=q.size();
14             while(s--)
15             {
16                 int x=q.front()>>8;
17                 int y=q.front()&0xFF;
18                 q.pop();
19                 for(auto d:dir)
20                 {
21                     int dx=x+d[0];
22                     int dy=y+d[1];
23                     if(dx==-1||dx==m||dy==-1||dy==n)
24                     ans=(ans+dp[x][y])%mod;
25                     else
26                     {
27                         if(dp[dx][dy]==0)q.push(dx<<8|dy);
28                         dp[dx][dy]=(dp[dx][dy]+dp[x][y])%mod;
29                     }
30                 }
31                 dp[x][y]=0;
32             }
33         }
34         return ans;
35     }
36 };

 

以上是关于2021-8-15 Out of Boundary Paths的主要内容,如果未能解决你的问题,请参考以下文章

576. Out of Boundary Paths

leetcode 576. Out of Boundary Paths

第十一周 Leetcode 576. Out of Boundary Paths (HARD) 计数dp

LeetCode 545. Boundary of Binary Tree

[LC] 545. Boundary of Binary Tree

[LeetCode] Boundary of Binary Tree 二叉树的边界