标签:
这个题没过……!
题意:小蚂蚁向四周走,让你在他走过的路中寻找最短路,其中可以反向
主要思路:建立想对应的图,寻找最短路径,其中错了好多次,到最后时间没过(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(1) * 4; using namespace std; int graph[200][200]; bool through[100][100]; int dr[] = {1,-1,0,0}; int dc[] = {0,0,-1,1}; bool visit[200][200]; struct Point{ int x,y; int step; Point(){ step = 0; } 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,0,sizeof(graph)); memset(through,0,sizeof(through)); memset(visit,0,sizeof(visit)); int x = 100; int y = 100; int sx = 100; int sy = 100; graph[x][y] = 1; 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]+1; through[ graph[x][y] ][graph[xx][yy] ] = 1; through[ graph[xx][yy] ][graph[x][y] ] = 1; x = xx; y = yy; } if(ww == 1){ cout << "1" << endl; continue; } while(!que.empty()){ que.pop(); } Point head(sx,sy,0); que.push(head); visit[sx][sy] = 1; while(!que.empty()){ Point tmp = que.front(); que.pop(); if(tmp.x == x && tmp.y == y){ cout << tmp.step << endl; break; } for(int i = 0;i < 4;i++){ int xx = tmp.x + dr[i]; int yy = tmp.y + dc[i]; if(graph[xx][yy] != 0 && through[ graph[tmp.x][tmp.y] ][ graph[xx][yy] ] && !visit[xx][yy]){ Point tt(xx,yy,tmp.step+1); que.push(tt); visit[xx][yy] = 1; } } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/hanbinggan/p/4256506.html