題目鏈接
題意
就是給你一個1000 * 1000以內的迷宮,只能轉彎兩次是否能夠從起點到終點。
解題思路
題意還是十分清晰的。以前沒做過轉彎的題目,所以花了比較久的時間。題目不能。在原來bfs的基礎上修改判斷
重複遍歷的條件。改爲轉彎次數是否小於前一次遍歷的次數。如果大於便不用進隊列了。因爲上次在已經轉彎的次
數小於這次的情況下都沒有走通,那麼這次次數少的情況下走依然不會走通。
代碼
#include <iostream>
#include <stdio.h>
#include <stack>
#include <queue>
#include <string.h>
using namespace std;
const int maxn = 1005;
int stepr[4] = {1,0,-1,0};
int stepl[4] = {0,1,0,-1};
char mymap[maxn][maxn];
int visit[maxn][maxn] = {0};
struct node
{
int x,y,times;
int type;
};
queue<node> s;
bool solve(int m, int n)
{
memset(visit, 3,sizeof(visit));
int sx,sy,ex,ey;
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j++)
{
if(mymap[i][j] == 'S')
{
sx = i;
sy = j;
}
if(mymap[i][j] == 'T')
{
ex = i;
ey = j;
}
}
node temp,next;
temp.times = 0;
temp.x = sx;
temp.y = sy;
temp.type = 4;
s.push(temp);
int tx,ty;
while(!s.empty())
{
temp = s.front();
s.pop();
if(temp.times > 2)
continue;
for(int i = 0; i < 4; i++)
{
tx = temp.x + stepr[i];
ty = temp.y + stepl[i];
if(tx >= 0 && tx < m && ty >= 0 && ty < n && mymap[tx][ty] != '*' && visit[tx][ty] > temp.times)
{
next.type = i;
if(i != temp.type && temp.type != 4)
next.times = temp.times+1;
else next.times = temp.times;
next.x = tx;
next.y = ty;
if(next.times > 2);
else s.push(next);
if(next.times > 2)
continue;
if(tx == ex && ty == ey)
return true;
visit[tx][ty] = next.times;
}
}
}
return false;
}
int main()
{
int m,n;
scanf("%d %d", &m,&n);
for(int i = 0; i < m; i++)
{
scanf("%s",mymap[i]);
}
if(solve(m,n))
{
cout << "YES" <<endl;
}
else cout << "NO" << endl;
return 0;
}