这份代码有什么问题#include <iostream> #include <string> using namespace std; int h, w, x, y, ddx = 0, ddy = 0; string s; char ch[20][20]; int dx[8] = { 0,1,1,1,0,-1,-1,-1 }; int dy[8] = { 1,1,0,-1,-1,-1,0,1 }; int main() { cin >> h >> w; for (int i = 1; i <= h; ++i) { cin >> s; for (int j = 0; j <= w - 1; ++j) ch[i][j + 1] = s[j]; } for (int i = 1; i <= h; ++i) { for (int j = 1; j <= w; ++j) { if (ch[i][j] == 's') { for (int k = 0; k < 8; ++k) { x = i + dx[k]; y = j + dy[k]; if (x >= 1 && x <= h && y >= 1 && y <= w && ch[x][y] == 'n') { ddx = dx[k]; ddy = dy[k]; if (x + ddx>=1&&x + ddx<=h&&x + ddx * 2>=1&&x + ddx * 2<=h&&x + ddx * 3>=1&&x + ddx * 3<=h&&y + ddy>=1&&y + ddy<=w&&y + ddy * 2>=1&&y + ddy * 2<=w&&y + ddy * 3>=1&&y + ddy * 3<=w && ch[x + ddx][y + ddy] == 'u' && ch[x + ddx * 2][y + ddy * 2] == 'k' && ch[x + ddx * 3][y + ddy * 3] == 'e') { cout << i << " " << j << endl; cout << i + ddx * 1 << " " <<j + ddy * 1 << endl; cout << i + ddx * 2 << " " <<j + ddy * 2 << endl; cout << i + ddx * 3 << " " <<j + ddy * 3 << endl; cout << i + ddx * 4 << " " <<j + ddy * 4 << endl; return 0; } } } } } } }
时间: 2023-12-03 18:43:26 浏览: 138
这份代码的问题在于循环变量 i 和 j 的范围,应该是从0到h-1和从0到w-1,而不是从1到h和从1到w,因为数组 ch 的下标是从0开始的。另外,变量 x 和 y 的初值也应该为 i 和 j,而不是 i+dx[k] 和 j+dy[k]。最后,如果没有找到符合要求的路径,应该输出 "impossible",而不是直接结束程序。修改后的代码如下:
```
#include <iostream>
#include <string>
using namespace std;
int h, w, x, y, ddx = 0, ddy = 0;
string s;
char ch[20][20];
int dx[8] = { 0,1,1,1,0,-1,-1,-1 };
int dy[8] = { 1,1,0,-1,-1,-1,0,1 };
int main() {
cin >> h >> w;
for (int i = 0; i < h; ++i) {
cin >> s;
for (int j = 0; j < w; ++j) ch[i][j] = s[j];
}
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
if (ch[i][j] == 's') {
for (int k = 0; k < 8; ++k) {
x = i; y = j;
ddx = dx[k]; ddy = dy[k];
if (x + ddx >= 0 && x + ddx <= h - 1 && x + ddx * 2 >= 0 && x + ddx * 2 <= h - 1 && x + ddx * 3 >= 0 && x + ddx * 3 <= h - 1 && y + ddy >= 0 && y + ddy <= w - 1 && y + ddy * 2 >= 0 && y + ddy * 2 <= w - 1 && y + ddy * 3 >= 0 && y + ddy * 3 <= w - 1 && ch[x + ddx][y + ddy] == 'u' && ch[x + ddx * 2][y + ddy * 2] == 'k' && ch[x + ddx * 3][y + ddy * 3] == 'e') {
cout << i + 1 << " " << j + 1 << endl;
cout << i + ddx + 1 << " " << j + ddy + 1 << endl;
cout << i + ddx * 2 + 1 << " " << j + ddy * 2 + 1 << endl;
cout << i + ddx * 3 + 1 << " " << j + ddy * 3 + 1 << endl;
cout << i + ddx * 4 + 1 << " " << j + ddy * 4 + 1 << endl;
return 0;
}
}
}
}
}
cout << "impossible" << endl;
return 0;
}
```
阅读全文