地址 https://algospot.com/judge/problem/read/JUMPGAME
每次我们可以选择 右或者下移动当前数字 x+num || y+num
但是遍历过于低效 会TLE
我们需要建立一个记录 记录当前的格子是否已经遍历过 如果已经遍历过直接取其记录的结果即可(当前格子是否已经遍历 遍历的结果是可以到达还是不能到达)
代码如下
1 #include <iostream> 2 #include <vector> 3 4 using namespace std; 5 6 /* 7 2 8 7 9 2 5 1 6 1 4 1 10 6 1 1 2 2 9 3 11 7 2 3 2 1 3 1 12 1 1 3 1 7 1 2 13 4 1 2 3 4 1 2 14 3 3 1 2 3 4 1 15 1 5 2 9 4 7 0 16 7 17 2 5 1 6 1 4 1 18 6 1 1 2 2 9 3 19 7 2 3 2 1 3 1 20 1 1 3 1 7 1 2 21 4 1 2 3 4 1 3 22 3 3 1 2 3 4 1 23 1 5 2 9 4 7 0 24 */ 25 vector<vector<int>> v(150,vector<int>(150)); 26 vector<vector<int>> vis(150, vector<int>(150)); 27 int n; int m; 28 29 int jump(int x,int y) 30 { 31 if (x >= m || x<0 || y <0 || y >= m) return -1; 32 if (vis[x][y] == 1) 33 return 0; 34 vis[x][y] = 1; 35 if (x == m - 1 && y == m - 1) 36 return 1; 37 int jumpcount = v[x][y]; 38 int ret1 = jump(x + jumpcount, y); 39 int ret2 = jump(x,y+ jumpcount); 40 41 if (ret1 == 1 || ret2 == 1) 42 return 1; 43 return -1; 44 } 45 46 47 void solve() 48 { 49 int x = 0, y = 0; 50 51 int ret = jump(0,0); 52 if (ret == 1) { 53 cout << "YES" << endl; 54 } 55 else { 56 cout << "NO" << endl; 57 } 58 } 59 60 int main() 61 { 62 cin >> n; 63 while (n--) { 64 for (int i = 0; i < 150; i++) 65 for (int j = 0; j < 150; j++) 66 v[i][j] = 0; 67 for (int i = 0; i < 150; i++) 68 for (int j = 0; j < 150; j++) 69 vis[i][j] = 0; 70 71 72 cin >> m; 73 for (int i = 0; i < m; i++) { 74 for (int j = 0; j < m; j++) { 75 cin >> v[i][j]; 76 } 77 } 78 79 solve(); 80 } 81 82 83 return 0; 84 }