Created
October 2, 2015 21:05
-
-
Save GnsP/17ed5d83c951f9db2fc0 to your computer and use it in GitHub Desktop.
Snake game DP problem given in some placement test I did for a friend XD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#define INF 1000000007 | |
using namespace std; | |
int dp[505][505][2]; // the storage for the DP (Dynamic programming) | |
int grid[505][505]; // the storage for the actual grid | |
void init(int n, int m){ // read from input and initialize the grid and | |
for(int i=0; i<n; i++){ // the DP arrays. | |
for(int j=0; j<m; j++){ | |
cin >> grid[i][j]; | |
if(grid[i][j] == -1) grid[i][j] = -INF; | |
if(j==0){ | |
dp[i][j][0] = grid[i][j]; | |
dp[i][j][1] = grid[i][j]; | |
} | |
else{ | |
dp[i][j][0] = -INF; | |
dp[i][j][1] = -INF; | |
} | |
} | |
} | |
} | |
int main(){ | |
int n, m, val; | |
cin >> n >> m; // read n and m | |
init(n, m); // the grid is read inside the init function | |
// Do the DP now | |
for(int j=0; j<m; j++){ | |
for(int i=n-1; i>0; i--) | |
if(grid[i-1][j] > -1) dp[i-1][j][1] = max(dp[i-1][j][1], dp[i][j][1]+grid[i-1][j]); | |
if(dp[0][j][1] > -1 && grid[n-1][j] > -1) dp[n-1][j][1] = max(dp[n-1][j][1], grid[n-1][j]); | |
for(int i=0; i<n-1; i++) | |
if(grid[i+1][j] > -1) dp[i+1][j][0] = max(dp[i+1][j][0], dp[i][j][0]+grid[i+1][j]); | |
if(grid[0][j] > -1 && dp[n-1][j][0] > -1) dp[0][j][0] = max(dp[0][j][0], grid[0][j]); | |
for(int i=0; i<n; i++){ | |
if(j+1 < m && grid[i][j+1] > -1){ | |
dp[i][j+1][0] = max(dp[i][j+1][0], max(dp[i][j][0], dp[i][j][1])+grid[i][j+1]); | |
dp[i][j+1][1] = max(dp[i][j+1][1], max(dp[i][j][0], dp[i][j][1])+grid[i][j+1]); | |
} | |
} | |
} | |
// DP done. Now just read the results from the DP array and print the maximum value. | |
int res = -1; | |
for(int i=0; i<n; i++) res = max(res, max(dp[i][m-1][0], dp[i][m-1][1])); | |
cout << res << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment