4kyu Path Finder #1: can you reach the exit?
题目背景:
Task
You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return true
if you can reach position [N-1, N-1] or false
otherwise.
Empty positions are marked .
, Walls are marked W
,Start and exit positions are empty in all test cases.
题目分析:
迷宫问题一般就是深搜,广搜,最短路径等经典的图论问题的应用场景,这种题目在OJ中算是基本题目,刷了些题目的看到这种题目就很熟悉了。本道题我用广搜去处理,其实广搜的代码很有套路,写了几遍就知道如何写更舒服了,对于这种题型,其实应用场景还是蛮好分析的,难点在于正确无误地快速码出经典的搜索代码。
AC代码:
#include <iostream>
#include <string>
#include <cmath>
#include <queue>
using namespace std;
int go[4][2] = {
0, 1,
0, -1,
1, 0,
-1, 0
};
struct Node {
int x, y;
};
queue<Node> Q;
bool BFS(int length, string maze) {
while( !Q.empty() ) {
Node now = Q.front();
Q.pop();
for ( int i = 0; i < 4; i++ ) {
int nx = now.x + go[i][0];
int ny = now.y + go[i][1];
if ( nx == length - 1 && ny == length - 1 ) return true;
if ( nx < 0 || nx >= length || ny < 0 || ny >= length ) continue;
if ( maze[nx * ( length + 1 ) + ny] == 'W' ) continue;
maze[nx * ( length + 1 ) + ny] = 'W'; // make the tag, have gone
Node tmp;
tmp.x = nx;
tmp.y = ny;
Q.push(tmp);
}
}
return false;
}
bool path_finder(string maze) {
int length = std::floor( std::sqrt( (double) maze.size() ) );
while(!Q.empty()) Q.pop();
maze[0] = 'W';
Node tmp;
tmp.x = tmp.y = 0;
Q.push(tmp);
return BFS(length, maze);
}