微软2016校园招聘4月在线笔试(第3题)
分析:
题目利用DP思想,dp[i][j][k]
表示robot跑到i
行j
列目前移动方向为k
时,所需要的最小的flip。其中0 <= i <= N
,0 <= j <= M
,k = right/down
// j-1 j // i-1 r` // | // i r``-- ?--> right // // i+1 ?
//dp[i][j][right] 可由dp[i][j-1][right]右移和dp[i-1][j][down]下移两种情况得到:
1. dp[i][j-1][right]右移一步,到dp[i][j][right],若maze[i][j] == ‘b’,则dp[i][j][right]=dp[i][j-1][right] +1;
2. dp[i-1][j][down]下移时,需要改变方向,先下移一步到第i行j列,此时方向是向下的,要变为向右,需考虑maze[i+1][j],若i+1==n(边界)或者maze[i+1][j] == ‘b’,则表示向下行不通,便直接改变方向向右;若第i+1行j列可以走的话,需将其变为’b’,使其行不通,才能改变方向为向右。故可表示为以下公式:
dp[i][j][right] = min(dp[i][j-1][right], dp[i-1][j][down] + (i+1 < n && maze[i+1][j] != ‘b’)) + (maze[i][j] == ‘b’);dp[i][j][down]同理如下;
// j-1 j j+1 // i-1 r` // | // i r``-- ? ? // | // v // down dp[i][j][down] = min(dp[i-1][j][down], dp[i][j-1][right] + (j+1 < m && maze[i][j+1] != 'b')) + (maze[i][j] == 'b');
Solution
下面是C++实现的完整代码:
#include <iostream> #include <vector> using namespace std; int solve(vector<vector<char>> &maze) { const int n = maze.size(); const int m = maze.front().size(); vector<vector<vector<int>>> dp(n, vector<vector<int>>(m, vector<int>(2))); dp[0][0][0] = maze[0][0] == 'b'; dp[0][0][1] = dp[0][0][0] + (1 < m && maze[0][1] != 'b'); for (int i = 1; i < n; ++i) { dp[i][0][1] = min(dp[i-1][0][0] + (1 < m && maze[i-1][1] != 'b'), dp[i-1][0][1]) + (maze[i][0] == 'b'); dp[i][0][0] = dp[i][0][1] + (i+1 < n && maze[i+1][0] != 'b'); } for (int i = 1; i < m; ++i) { dp[0][i][0] = min(dp[0][i-1][1] + (1 < n && maze[1][i-1] != 'b'), dp[0][i-1][0]) + (maze[0][i] == 'b'); dp[0][i][1] = dp[0][i][0] + (i+1 < m && maze[0][i+1] != 'b'); } for (int i = 1; i < n; ++i) { for (int j = 1; j < m; ++j) { dp[i][j][0] = min(dp[i][j-1][0], dp[i-1][j][1] + (i+1 < n && maze[i+1][j] != 'b')) + (maze[i][j] == 'b'); dp[i][j][1] = min(dp[i-1][j][1], dp[i][j-1][0] + (j+1 < m && maze[i][j+1] != 'b')) + (maze[i][j] == 'b'); } } return min(dp[n-1][m-1][0], dp[n-1][m-1][1]); } int main(void) { int n, m; while (cin >> n >> m) { vector<vector<char>> maze(n, vector<char>(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> maze[i][j]; } } cout << solve(maze) << endl; } }
Complexity
- 时间复杂度:O(n*m)
- 空间复杂度:O(n*m)
转自:http://www.gotit.sinaapp.com/wei-ruan-2016xiao-yuan-zhao-pin-4yue-zai-xian-bi-shi-ti-jie-san.html