Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #include <ext/pb_ds/assoc_container.hpp> // Common file
- #include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
- using namespace std;
- using namespace __gnu_pbds;
- typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
- #define IO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
- const int N = 1000, M = 1000;
- int arr[N + 3][M + 3];
- int dp[N + 3][M + 3];
- int dx[] = {1, -1, 0, 0};
- int dy[] = {0, 0, 1, -1};
- int n, m;
- bool isVal(int r, int c)
- {
- return r >= 1 && c >= 1 && r <= n && c <= m;
- }
- int solve(int r, int c)
- {
- if(r > n || c > m)
- return 1e7;
- if(r == n && c == m)
- return arr[n][m];
- if(dp[r][c] != -1)
- return dp[r][c];
- int ans = 1e7;
- for(int i = 0; i < 4; i++)
- {
- int rr = r + dx[i], cc = c + dy[i];
- if(isVal(rr, cc))
- ans = min(ans, arr[r][c] + solve(rr, cc));
- }
- return dp[r][c] = ans;
- }
- int main()
- {
- IO;
- int t;
- cin >> t;
- while(t--)
- {
- cin >> n >> m;
- for(int i = 1; i <= n; i++)
- {
- for(int j = 1; j <= m; j++)
- cin >> arr[i][j];
- }
- memset(dp, -1, sizeof dp);
- cout << solve(1, 1) << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement