蓝桥杯题库 小蓝的迷宫问题一 题解 算法 模拟

6413.小蓝的迷宫问题一

蓝桥杯题库 题目链接

模拟

题意,给出一个 n * n 的正方形迷宫,按照顺时针螺旋走位。当走到坐标(i, j)的时候走了多少步?
图片

按层模拟

可以将地图看成若干层,从外层向内层遍历。

对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于 (top,left),右下角位于 (bottom,right),按照如下顺序遍历当前层的元素。

  1. 从左到右遍历上侧元素,依次为 (top,left)(top,right)
  2. 从上到下遍历右侧元素,依次为 (top+1,right)(bottom,right)
  3. 从右到左遍历下侧元素,依次为 (bottom,right−1)(bottom,left+1)
  4. 从下到上遍历左侧元素,依次为 (bottom,left)(top+1,left)

遍历完当前层的元素之后,将 left 和 top 分别增加 1,将 right 和 bottom 分别减少 1,进入下一层继续遍历,直到遍历到目标坐标停止。

Java代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int I = scan.nextInt();
        int J = scan.nextInt();
        long ans = 1;

        int left = 1, right = n, top = 1, bottom = n;
        while (true) {
            for (int col = left; col <= right; col++) {
                if (top == I && col == J) {
                    System.out.println(ans);
                    return;
                }
                ans++;
            }
            for (int row = top + 1; row <= bottom; row++) {
                if (row == I && right == J) {
                    System.out.println(ans);
                    return;
                }
                ans++;
            }
            for (int col = right - 1; col > left; col--) {
                if (bottom == I && col == J) {
                    System.out.println(ans);
                    return;
                }
                ans++;
            }
            for (int row = bottom; row > top; row--) {
                if (row == I && left == J) {
                    System.out.println(ans);
                    return;
                }
                ans++;
            }
            left++;
            right--;
            top++;
            bottom--;
        }
    }
}
  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值