1. 程式人生 > 其它 >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 };