标签:limit ini style pst cep return struct span print
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 31544 | Accepted: 18065 |
Description
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
Input
Output
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
思路:
//用队列来广搜,然后走过的地方标记下并沿路建并查集,然后用并查集回溯并把点放到栈里,最后pop栈输出结果
代码:
#include <iostream> #include <queue> #include <stack> using namespace std; int graph[7][7];//存图 bool marked[7][7];//标记走过的点 struct pos { int x; int y; }; queue<pos> q; pos un[7][7];//并查集,用于找回路 stack<pos> s;//用于回路逆序输出 void init()//初始化 { pos t; for(int i = 0; i < 7; i++) { for(int j = 0; j < 7; j++) { t.x = i; t.y = j; un[i][j] = t; graph[i][j] = 1;//图周围放一圈墙 marked[i][j] = false; } } } void bfs()//广搜 { //创建起始点 pos p; p.x = p.y = 1; q.push(p); marked[1][1] = true; //搜索所有点 while(!q.empty()) { pos c = q.front(); q.pop(); pos t = c; t.x++; //搜索当前点周围的可走点并放入队列中 if(graph[t.x][t.y]==0 && !marked[t.x][t.y]) { q.push(t); marked[t.x][t.y]=true; un[t.x][t.y] = c; } t.x-=2; if(graph[t.x][t.y]==0 && !marked[t.x][t.y]) { q.push(t); marked[t.x][t.y]=true; un[t.x][t.y] = c; } t.x++; t.y++; if(graph[t.x][t.y]==0 && !marked[t.x][t.y]) { q.push(t); marked[t.x][t.y]=true; un[t.x][t.y] = c; } t.y-=2; if(graph[t.x][t.y]==0 && !marked[t.x][t.y]) { q.push(t); marked[t.x][t.y]=true; un[t.x][t.y] = c; } } } int main() { //初始化 init(); //输入 for(int i = 1; i <= 5; i++) { for(int j = 1; j <= 5; j++) cin >> graph[i][j]; } bfs(); pos t; t.x = t.y = 5; //利用并查集从终点回溯,并把点放入栈中 while(t.x != un[t.x][t.y].x || t.y != un[t.x][t.y].y) { s.push(t); t = un[t.x][t.y]; } t.x = t.y = 1; s.push(t); //pop栈,输出结果 while(!s.empty()) { t = s.top(); s.pop(); printf("(%d, %d)\n",t.x-1,t.y-1); } return 0; }
标签:limit ini style pst cep return struct span print
原文地址:https://www.cnblogs.com/w-j-c/p/9218897.html