这个题没过……!
题意:小蚂蚁向四周走,让你在他走过的路中寻找最短路,其中可以反向
主要思路:建立想对应的图,寻找最短路径,其中错了好多次,到最后时间没过(1.没有考录反向2.没有考虑走过的路要标记……!!!!!内存超了……啊啊啊啊!!!!)
总之,这样了~~
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <cctype> const double Pi = atan() * ;
using namespace std; int graph[][];
bool through[][];
int dr[] = {,-,,};
int dc[] = {,,-,};
bool visit[][];
struct Point{
int x,y;
int step;
Point(){
step = ;
}
Point(int xx,int yy,int tt):x(xx),y(yy),step(tt){}
};
int main()
{
freopen("input.in","r",stdin);
//freopen("output.in","w",stdout);
int t;
cin >> t;
queue<Point>que;
while(t--){
int n;
cin >> n;
memset(graph,,sizeof(graph));
memset(through,,sizeof(through));
memset(visit,,sizeof(visit));
int x = ;
int y = ;
int sx = ;
int sy = ;
graph[x][y] = ;
char ch;
int ww = n;
while(n--){
cin >> ch;
int xx = x;
int yy = y;
if(ch == 'E'){
xx++;
}
else if(ch == 'W'){
xx--;
}
else if(ch == 'S'){
yy--;
}
else if(ch == 'N'){
yy++;
}
if(!graph[xx][yy])
graph[xx][yy] = graph[x][y]+;
through[ graph[x][y] ][graph[xx][yy] ] = ;
through[ graph[xx][yy] ][graph[x][y] ] = ;
x = xx;
y = yy;
}
if(ww == ){
cout << "" << endl;
continue;
}
while(!que.empty()){
que.pop();
}
Point head(sx,sy,);
que.push(head);
visit[sx][sy] = ;
while(!que.empty()){
Point tmp = que.front();
que.pop();
if(tmp.x == x && tmp.y == y){
cout << tmp.step << endl;
break;
}
for(int i = ;i < ;i++){
int xx = tmp.x + dr[i];
int yy = tmp.y + dc[i];
if(graph[xx][yy] != && through[ graph[tmp.x][tmp.y] ][ graph[xx][yy] ] && !visit[xx][yy]){
Point tt(xx,yy,tmp.step+);
que.push(tt);
visit[xx][yy] = ;
}
}
}
}
return ;
}