以下是我的程式碼
中間有印出路徑測試都是沒問題的
但最後兩個資測答案卻錯誤
我的答案都印出no solution
不知問題出在哪裡
希望版友們不吝指教
#include<iostream>
using namespace std;
#include<queue>
int main() {
cin.tie(0);
cout.tie(0);
std::ios::sync_with_stdio(false);
int n;
cin>>n;
char a[n+2][n+2];
for(int i = 0; i < n+2; i++) {
a[i][0] = '#';
a[i][n+1] = '#';
a[0][i] = '#';
a[n+1][i] = '#';
}
for(int i = 1; i <= n; i++ )
for(int j = 1; j <= n; j++)
cin>>a[i][j];
queue<pair<int, int>> walk;
walk.push({2,2});
int step[n+2][n+2];
for(int i = 0; i <= n+1; i++ )
for(int j = 0; j <= n+1; j++)
step[i][j] = 0;
step[2][2] = 1;
while(!walk.empty()) {
if(a[walk.front().first+1][walk.front().second] == '.') {
walk.push({walk.front().first+1,walk.front().second});
step[walk.back().first][walk.back().second] = step[walk.front().first][walk.front().second] + 1;
}
if(a[walk.front().first-1][walk.front().second] == '.') {
walk.push({walk.front().first-1,walk.front().second});
step[walk.back().first][walk.back().second] = step[walk.front().first][walk.front().second] + 1;
}
if(a[walk.front().first][walk.front().second+1] == '.') {
walk.push({walk.front().first,walk.front().second+1});
step[walk.back().first][walk.back().second] = step[walk.front().first][walk.front().second] + 1;
}
if(a[walk.front().first][walk.front().second]-1 == '.') {
walk.push({walk.front().first,walk.front().second-1});
step[walk.back().first][walk.back().second] = step[walk.front().first][walk.front().second] + 1;
}
for(int i = 1; i <= n; i++ ) {
for(int j = 1; j <= n; j++)
cout<<step[i][j]<<" ";
cout<<endl;
}
cout<<endl;
a[walk.front().first][walk.front().second] = '#';
walk.pop();
}
if(step[n-1][n-1] == 0)
cout<<"No solution!";
else
cout<<step[n-1][n-1];
return 0;
}