Java教程

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

 

这篇关于2021-8-15 Out of Boundary Paths的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!