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;
    }
    
  • 相关阅读:
    HDU1720 A+B Coming
    HDU1390 ZOJ1383 Binary Numbers
    HDU1390 ZOJ1383 Binary Numbers
    HDU2504 又见GCD
    HDU2504 又见GCD
    HDU1335 POJ1546 UVA389 UVALive5306 ZOJ1334 Basically Speaking
    HDU1335 POJ1546 UVA389 UVALive5306 ZOJ1334 Basically Speaking
    HDU1020 ZOJ2478 Encoding
    HDU1020 ZOJ2478 Encoding
    HDU2097 Sky数
  • 原文地址:https://www.cnblogs.com/zach20040914/p/12814355.html
Copyright © 2011-2022 走看看