[蓝桥杯]真题讲解:AB路线(BFS+分层图)

news2024/10/6 8:37:29

[蓝桥杯]真题讲解:AB路线(BFS+分层图)

  • 一、视频讲解
  • 二、正解代码
    • 1、C++
    • 2、python3
    • 3、Java

一、视频讲解

[蓝桥杯]真题讲解:AB路线(BFS+分层图)

在这里插入图片描述

二、正解代码

1、C++

#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int N = 1e3 + 10;
int g[N][N];
bool st[N][N][20];
int dis[N][N][20];

int n, m, k;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

bool check(int x, int y) {
	return x >= 0 && x < n && y >= 0 && y < m;
}

int bfs() {
	for(int i = 0; i < n; i ++) {
		for(int j = 0; j < m; j ++) {
			for(int p = 0; p < k; p ++) {
				dis[i][j][p] = INF;
			}
		}
	}
	queue<array<int,3>>q;
	q.push({0, 0, 1});
	dis[0][0][1] = 1;
	st[0][0][1] = true;
	while(q.size()){
		auto t = q.front();
		q.pop();
		int x = t[0], y = t[1], cnt = t[2];
		int d = dis[x][y][cnt];

		for(int i = 0; i < 4; i ++) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			int nc = (d / k) % 2;
			if(check(nx, ny) && g[nx][ny] == nc && !st[nx][ny][(d + 1) % k]) {
				st[nx][ny][(d + 1) % k] = true;
				q.push({nx, ny, (d + 1) % k});

				dis[nx][ny][(d + 1) % k] = d + 1;
			}
		}
	}
	
	int minv = INF;
	for(int i = 0; i < k; i ++) {
		minv = min(minv, dis[n - 1][m - 1][i]);
	}
	return minv;
}

void solve(){
	cin >> n >> m >> k;
	for(int i = 0; i < n; i ++) {
		string s; cin >> s;
		for(int j = 0; j < m; j ++) {
			g[i][j] = (s[j] != 'A');
		}
	}

	int res = bfs();
	if(res == INF){
		cout << -1 << endl;
	}else{
		cout << res - 1 << endl;
	}

}

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t = 1;
	while(t--){
		solve();
	}
	return 0;
}

2、python3

from collections import deque
INF = 0x3f3f3f3f
N = 1010
n, m, k = map(int, input().split())
st = [[[False] * 20 for _ in range(N)] for _ in range(N)]
dis = [[[INF] * 20 for _ in range(N)] for _ in range(N)]
g = [[0] * N for _ in range(N)]
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

def check(x, y):
    return x >= 0 and x < n and y >= 0 and y < m

def bfs():
    q = deque([(0, 0, 1)])
    dis[0][0][1] = 1
    st[0][0][1] = True
    while q:
        x, y, cnt = q[0]
        q.popleft()
        d = dis[x][y][cnt]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            nc = (d // k) % 2
            if check(nx, ny) and g[nx][ny] == nc and st[nx][ny][(d + 1) % k] == False:
                st[nx][ny][(d + 1) % k] = True
                q.append((nx, ny, (d + 1) % k))
                dis[nx][ny][(d + 1) % k] = d + 1
    minv = INF
    for i in range(k):
        minv = min(minv, dis[n - 1][m - 1][i])
    return minv


for i in range(n):
    s = input()
    for j in range(m):
        if s[j] != 'A':
            g[i][j] = 1
        else:
            g[i][j] = 0
res = bfs()
if res == INF:
    print(-1)
else:
    print(res - 1)

3、Java

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class ABRoad {

    public static final int INF = 0x3f3f3f3f;
    public static int[] dx = new int[]{-1, 0, 1, 0};
    public static int[] dy = new int[]{0, 1, 0, -1};
    public static int n, m, k;
    public static int[][] g;
    public static boolean[][][] st;
    public static int[][][] dis;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        k = sc.nextInt();
        g = new int[n + 10][m + 10];
        st = new boolean[n + 10][m + 10][k + 10];
        dis = new int[n + 10][m + 10][k + 10];
        for(int i = 0; i < n; i ++ ) {
            String s;
            s = sc.next();
            for(int j = 0; j < m; j ++) {
                if(s.charAt(j) != 'A')
                    g[i][j] = 1;
                else
                    g[i][j] = 0;
            }
        }
        int res = bfs();
        if(res == INF)
            System.out.println(-1);
        else
            System.out.println(res - 1);
    }

    private static int bfs() {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                for (int p = 0; p < k; p++) {
                    dis[i][j][p] = INF;
                }
            }
        }
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{0, 0, 1});
        dis[0][0][1] = 1;
        st[0][0][1] = true;
        while (!q.isEmpty()) {
            int[] t = q.poll();
            int x = t[0], y = t[1], cnt = t[2];
            int d = dis[x][y][cnt];
            for (int i = 0; i < 4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                int nc = (d / k) % 2;
                if (check(nx, ny) && g[nx][ny] == nc && !st[nx][ny][(d + 1) % k]) {
                    st[nx][ny][(d + 1) % k] = true;
                    q.add(new int[]{nx, ny, (d + 1) % k});
                    dis[nx][ny][(d + 1) % k] = d + 1;
                }
            }
        }
        int minv = INF;
        for(int i = 0; i < k; i ++) {
            minv = Math.min(minv, dis[n - 1][m - 1][i]);
        }
        return  minv;
    }
    private static boolean check(int x, int y) {
        return x >= 0 && x < n && y >= 0 && y < m;
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1665819.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

大数据Scala教程从入门到精通第八篇:Scala在IDEA中编写Hello World

一&#xff1a;Scala在IDEA中编写Hello World object HelloWorld {def main(args: Array[String]): Unit {println("hello world")}}这个对象也单例的。 特殊的Java类库需要import

【Java 查询树结构列表,递归删除子节点】

Java 获取列表树结构&#xff0c;递归删除子节点 数据库表结构ModelVO查询树结构列表递归删除子节点 数据库表结构 Model Data AllArgsConstructor NoArgsConstructor public class TBaseDept {/** ID */private String id;/** 单位名称 */private String fdName;/** 部门编码…

Python | Leetcode Python题解之第84题柱状图中最大的矩形

题目&#xff1a; 题解&#xff1a; class Solution:def largestRectangleArea(self, heights: List[int]) -> int:n len(heights)left, right [0] * n, [n] * nmono_stack list()for i in range(n):while mono_stack and heights[mono_stack[-1]] > heights[i]:righ…

scanf留下的那一片云彩

【题目描述】 给出一个由O和X组成的串&#xff08;长度为1&#xff5e;80&#xff09;&#xff0c;统计得分。每个O的得分为目前连续出现的O的个数&#xff0c;X的得分为0。例如&#xff0c;OOXXOXXOOO的得分为1200100123。 输入第一行表示有n个字符串&#xff0c;后续是n行字…

1056: 邻接表到邻接矩阵

解法&#xff1a; #include<iostream> #include<vector> #include<string> using namespace std; int arr[100][100]; int main() {int n;cin >> n;getchar();vector<string> s(n);for (int i 0; i < n; i) {getline(cin, s[i]);}for (int …

进程间通信:连接不同程序世界的桥梁

目录 一、进程间通信的重要性 二、常见的进程间通信方式 三、进程间通信的目的 四、进程间通信的本质 在计算机编程的领域中&#xff0c;进程间通信&#xff08;Inter-Process Communication&#xff0c;IPC&#xff09;是一个至关重要的概念。当我们在操作系统中运行多个程…

数据结构之——队列详解

目录 前言&#xff1a; 一、什么是队列 二、队列的实现 2.1 队列结构 2.2 队列初始化 2.3 队列销毁 2.4 入队列 2.5 出队列 2.6 获取队列头部元素 2.7 获取队列尾部元素 2.8 获取队列中有效元素个数 2.9 检测队列是否为空 三、 代码总览 Queue.h test.c 四、例题 前言…

Base64在线编码解码方法

Base64在线编码解码 打开网站 在线工具网-梦幻加菲猫 选择“Base64编码解码” 输入需要编码/解码的内容&#xff0c;点击“编码”/“解码”按钮 编码&#xff1a; 解码&#xff1a; 4. 复制已经编码/解码后的内容。

大数据交通行政执法监测系统

交通行政执法监测系统应用系统按照监测主体可分为&#xff1a;出租车交通违法监测&#xff0c;客车交通违法监测&#xff0c;货车、危化品车辆交通违法监测&#xff0c;非法营运车辆监测。功能模块涵盖&#xff1a;特征识别、档案查询、预警分析等。 &#xff08;1&#xff09;…

腾讯云服务器之ssh远程连接登录及转发映射端口实现内网穿透(实现服务器访问本地电脑端口)

目录 一、创建密钥绑定实例二、设置私钥权限三、ssh远程连接到服务器四、修改root密码五、端口转发&#xff08;实现服务器访问本地电脑的端口&#xff09; 一、创建密钥绑定实例 创建密钥会自动下载一个私钥&#xff0c;把这个私钥复制到c盘 二、设置私钥权限 1、删除所有用户…

前端笔记-day04

文章目录 01-后代选择器02-子代选择器03-并集选择器04-交集选择器05-伪类选择器06-拓展-超链接伪类07-CSS特性-继承性08-CSS特性-层叠性09-CSS特性-优先级11-Emmet写法12-背景图13-背景图平铺方式14-背景图位置15-背景图缩放16-背景图固定17-background属性18-显示模式19-显示模…

NPOI生成word浮动图标

1、NPOI版本2.7.0, net框架4.8 2、安装OpenXMLSDKToolV25.msi 3、先创建一个word文档&#xff0c;并设置图片为浮于文字之上 4、OpenXML显示的结果 5、实际代码如下&#xff1a; public class GenerateWordDemo {public GenerateWordDemo(){}//https://blog.fileformat.co…

word-排版文本基本格式

1、文本的基本格式&#xff1a;字体格式、段落格式 2、段落&#xff1a;word排版的基本控制单位 3、每敲一次回车&#xff0c;为一个段落标记&#xff0c;注意区分换行符和段落标记&#xff0c;换行符为指向下的箭头&#xff0c;段落标记为带拐弯的箭头&#xff0c;换行符&…

C语言基础——循环语句

&#x1f33a;​&#x1f64f;&#x1f64f;&#x1f64f;欢迎大家观看&#xff0c;写的好的话希望三连感谢&#x1f64f;&#x1f64f;&#x1f64f;&#x1f33a; 文章目录 一、循环语句的介绍 二、不同循环语句的使用 1.while循环 1.1 while循环的使用方式 1.2 while循环的执…

Java | Leetcode Java题解之第84题柱状图中最大的矩形

题目&#xff1a; 题解&#xff1a; class Solution {public int largestRectangleArea(int[] heights) {int n heights.length;int[] left new int[n];int[] right new int[n];Arrays.fill(right, n);Deque<Integer> mono_stack new ArrayDeque<Integer>();f…

https免费证书获取

获取免费证书的网址&#xff1a; Certbot 1. 进入你的linux系统&#xff0c;先安装snapd&#xff0c; yum install snapd 2. 启动snapd service snapd start 3.安装 Certbot snap install --classic certbot 注意如下出现此错误时&#xff0c;需要先建立snap 软连接后&am…

MVCC 详解

介绍 MVCC&#xff0c;全称 Multi-Version Concurrency Control&#xff0c;即多版本并发控制 MVCC的目的主要是为了提高数据库并发性能&#xff0c;用更好的方式去处理读-写冲突&#xff0c;做到即使有读写冲突时&#xff0c;也能做到不加锁。 这里的多版本指的是数据库中同时…

Ubuntu 和 Windows之间无法复制粘贴问题解决方法

需要安装open-vm-tools&#xff0c;官方安装open-vm-tools的网址&#xff1a;安装 Open VM Tools (vmware.com)

vue 点击平滑到指定位置并绑定页面滑动效果

1.html元素 写出对应的数据块&#xff08;注意添加ref) 用于获取元素位置 <template><div class"index-page" ><div class"top-head" ref"index"><img src"logo.png" style"height: 40px;margin-right: 2…

代码+视频,R言语处理数据中的缺失值

在SCI论文中&#xff0c;我们不可避免和缺失数据打交道&#xff0c;特别是在回顾性研究&#xff0c;对于缺失的协变量&#xff08;就是混杂因素&#xff09;&#xff0c;我们可以使用插补补齐数据&#xff0c;但是对于结局变量和原因变量的缺失&#xff0c;我们不能这么做。部分…