4kyu Path Finder #2: shortest path

4kyu Path Finder #2: shortest path

题目背景:

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 the minimal number of steps to exit position [N-1, N-1] if it is possible to reach the exit from the starting position. Otherwise, return false in JavaScript/Python and -1 in C++/C#/Java.

Empty positions are marked .. Walls are marked W. Start and exit positions are guaranteed to be empty in all test cases.

题目分析:

迷宫问题一般就是深搜,广搜,最短路径等经典的图论问题的应用场景,这种题目在OJ中算是基本题目,刷了些相关题目后看到这种题目就很熟悉了。本道题我用广搜去处理,从起点一层一层地往外剥,对于走过的格点都打上tag,每一个格点再附上到达这个格点的步数属性,这样广搜到终点的话就可以获取到步数。

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;
    int steps;
};

queue<Node> Q;

int 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 ++now.steps;
            if ( nx < 0 || nx >= length || ny < 0 || ny >= length ) continue;
            if ( maze[nx * ( length + 1 ) + ny]  == 'W' ) continue;
            maze[nx * ( length + 1 ) + ny] = 'W';
            Node tmp;
            tmp.x = nx;
            tmp.y = ny;
            tmp.steps = now.steps + 1;
            Q.push(tmp);
        }
    }
    return -1;
}

int path_finder(string maze) {
    int length = std::floor( std::sqrt( (double) maze.size() ) );
    if ( length  == 1 ) return 0;
    while(!Q.empty()) Q.pop();
    maze[0] = 'W';
    Node tmp;
    tmp.x = tmp.y = tmp.steps = 0;
    Q.push(tmp);
    return BFS(length, maze);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值