其他分享
首页 > 其他分享> > 2021-8-15 Out of Boundary Paths

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 };

 

标签:Paths,ball,15,int,startRow,grid,dx,dy,Boundary
来源: https://www.cnblogs.com/lovetianyi/p/15145424.html