zoukankan      html  css  js  c++  java
  • 洛谷 P1443 马的遍历

    题目:马的遍历

    网址:https://www.luogu.com.cn/problem/P1443

    题目描述

    有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步?

    输入格式

    一行四个数据,棋盘的大小和马的坐标

    输出格式

    一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)

    输入输出样例
    输入
    3 3 1 1
    
    输出
    0    3    2    
    3    -1   1    
    2    1    4    
    

    Flood-fill 标准题目。需要判重。

    代码如下:

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<cmath>
    #include<queue>
    #define MAX_size 400 + 10
    using namespace std;
    const int dx[8] = {-2 , -1 , 1 , 2 , 2 , 1 , -1 , -2};
    const int dy[8] = {1 , 2 , 2 , 1 , -1 , -2 , -2 , -1};
    struct pos
    {
    	int x , y;
    } st;
    int n , m , d[MAX_size][MAX_size];
    bool valid(int x , int y)
    {
    	if(x < 1 || x > n || y < 1 || y > m) return false;
    	if(d[x][y] != -1) return false;
    
    	return true;
    }
    void bfs()
    {
    	queue <pos> Q;
    	while(!Q.empty()) Q.pop();
    	d[st.x][st.y] = 0;
    	Q.push(st);
    	while(!Q.empty())
    	{
    		pos now = Q.front();
    
    		Q.pop();
    		for(int i = 0; i < 8; ++ i)
    		{
    			int x = now.x + dx[i] , y = now.y + dy[i];
    			if(valid(x , y))
    			{
    				pos next = (pos) {x , y};
    				d[x][y] = d[now.x][now.y] + 1;
    				Q.push(next);
    			}
    		}
    	}
    }
    int main()
    {
    	scanf("%d %d %d %d" , &n , &m , &st.x , &st.y);
    	memset(d , -1 , sizeof(d));
    	bfs();
    	for(int i = 1; i <= n; ++ i)
    	{
    		for(int j = 1; j <= m; ++ j) printf("%-5d" , d[i][j]);
    		puts("");
    	}
    	return 0;
    }
    
  • 相关阅读:
    Swift # Apple Pay集成
    GitHub Top 100 简介
    一些常用算法
    CocoaPods 建立私有仓库
    安装 CocoaPods & Alcatraz
    iOS程序 # 启动过程
    Apache & WebDav 配置(二)
    SVN & Git (二)
    SVN & Git (一)
    poj 3169 Layout (差分约束)
  • 原文地址:https://www.cnblogs.com/zach20040914/p/12814355.html
Copyright © 2011-2022 走看看