#1290 : Demo Day
描述
You work as an intern at a robotics startup. Today is your company's demo day. During the demo your company's robot will be put in a maze and without any information about the maze, it should be able to find a way out.
The maze consists of N * M grids. Each grid is either empty(represented by '.') or blocked by an obstacle(represented by 'b'). The robot will be release at the top left corner and the exit is at the bottom right corner.
Unfortunately some sensors on the robot go crazy just before the demo starts. As a result, the robot can only repeats two operations alternatively: keep moving to the right until it can't and keep moving to the bottom until it can't. At the beginning, the robot keeps moving to the right.
rrrrbb.. ...r.... ====> The robot route with broken sensors is marked by 'r'. ...rrb.. ...bb...
While the FTEs(full-time employees) are busy working on the sensors, you try to save the demo day by rearranging the maze in such a way that even with the broken sensors the robot can reach the exit successfully. You can change a grid from empty to blocked and vice versa. So as not to arouse suspision, you want to change as few grids as possible. What is the mininum number?
输入
Line 1: N, M.
Line 2-N+1: the N * M maze.
For 20% of the data, N * M <= 16.
For 50% of the data, 1 <= N, M <= 8.
For 100% of the data, 1<= N, M <= 100.
输出
The minimum number of grids to be changed.
- 样例输入
-
4 8 ....bb.. ........ .....b.. ...bb...
- 样例输出
-
1
题目的意思是:
给你一个矩阵由‘.’和'b'组成 ‘.’表示可以走,'b'表示障碍物,机器人只能往右走直到不能走(碰到障碍物或者到头)和往下走直到不能走,两个方向,起始点是左上角,出口是右下角,为了机器人
能够走到出口,你可以将'.'变为'b', 也可以将'b'变为'.',,求为了使机器人走到出口,最少的变换次数。
(机器人从起点,一开始是往右走的,记住!!!!!!!)
思路:
应该算是动态规划吧,对于每一个点,到达这个点只能是经过上方点,或者从左方点到达该点,那么对于每一个点,一开始想的是用f[i][j],表示到达(i,j)需要变动的最小次数,但是发现到达每一个点是有方向的
,而且如果只用f[i][j],表示到达(i,j)的最小变动次数,不知道方向的话是无法递推下一个点的,所以,
我们用up[i][j],表示从上方到达该点需要变动的最小次数,r[i][j]表示从左方到达该点需要变动的最小次数,(i-1,j) (i - 1,j+1) (i,j) 对于up[i][j],可以是从左方到达(i-1, j),再到达(i,j),但此时(i-1, j+1)必须为'b'或者边界,也可以从上方到达(i-1,j)再到达(i,j);
还有就是如果(i,j)本身为'b'的话,则需要up[i][j]+1;
up[i-1][j]
up[i][j] = min
r[i-1][j] + 1(如果(i-1,j)不为‘b’或者边界则需要+1);
同理可得:
up[i][j-1] (+1) (如果(i+1,j-1)不为'b'或者边界,则需要+1)
r[i][j] = min
r[i][j-1]
为了处理方便在输入时,在矩阵的最右边和最下边添加了一行,一列'b';1 #include <iostream> 2 #include <stdio.h> 3 #include <string> 4 #include <string.h> 5 #include <algorithm> 6 #include <vector> 7 #define maxn 110 8 #define inf 9999999 9 using namespace std; 10 int n, m; 11 int r[maxn][maxn]; 12 int up[maxn][maxn]; 13 char str[maxn][maxn]; 14 int GetUp(int i, int j) 15 { 16 int x = r[i - 1][j]; 17 int y = up[i - 1][j]; 18 19 if(str[i-1][j+1]!= 'b')x++; 20 int ans = min(x,y); 21 return ans; 22 23 } 24 int GetR(int i, int j) 25 { 26 int x = r[i][j - 1]; 27 int y = up[i][j - 1]; 28 if(str[i+1][j - 1]!='b')y++; 29 return min(x,y); 30 } 31 int main() 32 { 33 while(scanf("%d%d", &n,&m)!=EOF) 34 { 35 for(int i = 0 ; i < n;i++) 36 { 37 scanf("%s", str[i]); 38 int len = strlen(str[i]); 39 str[i][len] = 'b'; 40 str[i][len+1] = '