17084 罗密欧与朱丽叶的迷宫问题

#include <iostream>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<math.h>
#include <algorithm>
#include<cstdlib>
#include<vector>

//八个方向
int* dirX = new int[8] {-1, -1, -1, 0, 0, 1, 1, 1};
int* dirY = new int[8] {-1, 0, 1, -1, 1, -1, 0, 1};
//n行m列,k个不能走的格子个数
int n, m, k;
//已经走过的能走的格子个数
int complete = 0;
//全图
int** map;
//判断最后是否有答案
bool flag = false;
//当前位置,目标位置
int curX, curY, targetX, targetY;
//最小转向次数的相同方案个数
int minSameAns = 0;
//最小转向次数
int minTurn = 2e7;

//当前位置,转向次数,正在使用的方向
void dfs(int curX,int curY,int turn,int curDir) {
    //如果转向次数比最小的还大,不用走了,剪枝
    if (turn > minTurn) {
        return;
    }
    //如果complete == n*m-k说明所有要走的格子走完了,并且当前位置是目标位置
    if (complete == n*m-k && curX==targetX && curY==targetY) {
        //找到了,标志flag
        flag = true;
        //如果当前ture==min,那么minSameAns直接加1,方案+1
        if (turn == minTurn) {
            minSameAns++;
        }
        else if(turn<minTurn){
            //如果turn小于min,那么设置当前turn为min
            minTurn = turn;
            //重置方案个数为1
            minSameAns = 1;
        }
        //返回
        return;
    }
    else{
        //如果没走到最后
        //判断当前能走的位置
        for (int i = 0; i < 8; i++) {
            int nextX = curX + dirX[i];
            int nextY = curY + dirY[i];
            //如果越界了,或者走过了,或者不能走的格子,跳过
            if (nextX <= 0 || nextX > n || nextY<=0 || nextY > m || map[nextX][nextY]==1|| map[nextX][nextY] == -1) {
                continue;
            }
            //位置能走,设置走过了
            map[nextX][nextY] = 1;
            //完成个数+1
            complete++;
            //如果还是原来的方向
            if (curDir == i) {
                //turn不变
                dfs(nextX,nextY,turn,i);
            }else {
                //如果不是原来的方向了,turn+1
                dfs(nextX, nextY, turn+1, i);
            }
            //回溯
            //完成个数-1
            complete--;
            //置0
            map[nextX][nextY] = 0;
        }
    }


}

int main() {
    cin >> n >> m >> k;
    map = new int*[n+1];
    for (int i = 0; i<=n; i++) {
        map[i] = new int[m+1] {0};
    }
    for (int i = 0; i<k; i++) {
        int x, y;
        cin >> x >> y;
        map[x][y] = -1;
    }
    cin >> curX >> curY >> targetX >> targetY;
    //注意这里,起始原点也要标志为已走
    map[curX][curY] = 1;
    //起始原点也算一个,所以complete++
    complete++;
    //递归,传入当前位置,转向次数,使用的转向序号    -1 8表示不存在
    dfs(curX,curY,-1,8);
    //如果flag为true,说明有答案,输出
    if (flag) {
        cout << minTurn << endl << minSameAns;
    }
    else {
        //flag不为true,没答案
        cout <<"No Solution!";
    }

    return 0;
}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值