Topic Description
Now there's a city sales manager, need to start from the company, to visit the city's businesses, known his location and the location of the business, but because of urban road traffic, he can only choose a direction in the left and right, select a direction in the top and bottom, now ask him how many options to reach the merchant address.
Given a map and its width n and M, where 1 represents the manager position, 2 represents the merchant position,-1 represents the area that cannot be passed, 0 represents the area that can be passed, please return the number of scenarios to ensure there is a legitimate path. Ensure that the length of the matrix is less than or equal to 10. Test Sample:
[[0,1,0],[2,0,0]],2,3
Return: 2
The idea of solving problems: using dynamic planning, assuming that 1 is in the upper-left corner and 2 in the lower-right corner, the manager can only go right or down. Initialize the columns and rows that are in the 1 first, all initialized to 1 before 1, and then all 0. Then the number of methods to go to each point is calculated, and then the number of methods to target is known.
Class Visit {public:int Countpath (vector<vector<int> > map, int n, int m) {//write code
here int startx =-1, starty =-1;
int endx =-1, Endy =-1; for (int i = 0; i < n; i++) {for (int j = 0; J < m; J +) {if map[
I][J] = = 1) {startx = i;
Starty = j;
} if (map[i][j] = = 2) {endx = i;
Endy = j;
} if (StartX!=-1 && endx!=-1) break; int diffx = startx > EndX?
-1:1; int diffy = starty > Endy?
-1:1; for (int i = startx + diffx i!= EndX + diffx i + = diffx) Map[i][starty] = Map[i][starty] = = 1?
0:map[i-diffx][starty]; for (int i = starty + diffy i!= Diffy + endy i + = diffy) map[StartX] [i] = map[startx][i] = =-1?
0:map[startx][i-diffy]; for (int i = startx + diffx i!= EndX + diffx i + = DIFFX) {for (int j = Starty + Diffy; J!= Endy + Diffy;
j = = Diffy) {Map[i][j] = map[i][j] = = 1? 0:map[i][j-diffy] + map[i-diffx][j];
} return Map[endx][endy]; }
};