普及练习场 广度优先搜索 马的遍历

题目链接

解题思路

这题主要就是写个裸的广度优先遍历。我在看了数据量之后果断选择了手写队列,加输入挂,奈何还是不行,其实动脑子都知道主要是要开输出挂。在开了输出挂之后就全过掉了。

代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {
    public static class FastScanner{
        private BufferedReader br;
        private StringTokenizer st;
        public FastScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public String nextToken()  {
            while(st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.valueOf(nextToken());
        }
    }
    static int N, M;
    static int sx, sy;
    static boolean[][] visited;
    static int[][] steps;
    static int[] dx = {-2, -2, -1, -1, 1, 1, 2, 2};
    static int[] dy = {-1, 1, -2, 2, -2, 2, -1, 1};
    static int[] qx = new int[200000];
    static int[] qy = new int[200000];
    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        PrintWriter writer = new PrintWriter(System.out);
        N = fs.nextInt();
        M = fs.nextInt();
        visited = new boolean[N+1][M+1];
        steps = new int[N+1][M+1];
        for(int i = 1; i <= N; i++) {
            for(int j = 1; j <= M; j++) {
                visited[i][j] = false;
                steps[i][j] = 0;
            }
        }
        sx = fs.nextInt();
        sy = fs.nextInt();
        int l, r;
        l = r = 0;
        visited[sx][sy] = true;
        qx[r] = sx;
        qy[r] = sy;
        while(l <= r) {
            int tx = qx[l];
            int ty = qy[l];
            for(int i = 0; i < 8; i++) {
                int nx = tx + dx[i];
                int ny = ty + dy[i];
                if(1 <= nx && nx <= N && 1 <= ny && ny <= M) {
                    if(!visited[nx][ny]) {
                        visited[nx][ny] = true;
                        steps[nx][ny] = steps[tx][ty] + 1;
                        qx[++r] = nx;
                        qy[r] = ny;
                    }
                }
            }
            l++;
        }
        for(int i = 1; i <= N; i++) {
            for(int j = 1; j <= M; j++) {
                if(visited[i][j]) {
                    writer.printf("%-5d", steps[i][j]);
                } else {
                    writer.printf("%-5d", -1);
                }
            }
            writer.println();
        }
        writer.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值