题目链接:马的遍历
java代码:
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static int n,m,r,c;
public static int dx[] = {-1,-2,-2,-1,1,2,2,1},dy[] = {2,1,-1,-2,2,1,-1,-2};
public static int a[][] = new int[410][410];
public static Queue<Integer> q = new LinkedList<>();
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
n = in.nextInt(); m = in.nextInt();
r = in.nextInt(); c = in.nextInt();
for(int i=0;i<410;++i) Arrays.fill(a[i], -1);
bfs();
for(int i=1;i<=n;++i) {
for(int j=1;j<=m;++j) {
System.out.printf("%-5d",a[i][j]);
}
System.out.println();
}
}
public static void bfs() {
q.add(r);
q.add(c);
a[r][c] = 0;
while(q.isEmpty()==false) {
int row = q.poll(), col = q.poll();
for(int i=0;i<8;++i) {
int x = row+dx[i], y = col+dy[i];
if(x>=1&&x<=n&&y>=1&&y<=m&&a[x][y]==-1) {
q.add(x);
q.add(y);
a[x][y] = a[row][col]+1;
}
}
}
}
}
|