这几天日常一搜索qaq
P1443 马的遍历
1 #include<cstdio> 2 #include<iostream> 3 using namespace std; 4 const int sz = 410; 5 int n, m, sx, sy; 6 int plat[sz][sz], q[sz*100][3]; 7 bool book[sz][sz]; 8 int dx[8] = {-2,-1,1,2,2,1,-1,-2}, 9 dy[8] = {1,2,2,1,-1,-2,-2,-1}; 10 void bfs(int x, int y) { 11 int head = 1, tail = 1, mx, my; 12 plat[x][y] = 0; 13 book[x][y] = 1; 14 q[1][1] = x, q[1][2] = y; 15 while(head <= tail) { 16 int step = plat[q[head][1]][q[head][2]]+1; 17 for(int i = 0; i < 8; i++) { 18 mx = q[head][1] + dx[i]; 19 my = q[head][2] + dy[i]; 20 if(mx>=1&&my>=1&&mx<=n&&my<=m&&(!book[mx][my])) { 21 tail++; 22 plat[mx][my] = step; 23 book[mx][my] = 1; 24 q[tail][1] = mx; 25 q[tail][2] = my; 26 } 27 } 28 head++; 29 } 30 31 } 32 int print() { 33 for(int i = 1; i <= n; i++) { 34 for(int j = 1; j <= m; j++) { 35 if(plat[i][j] == 0 ) { 36 if(i==sx&&j==sy) plat[i][j] = 0; 37 else plat[i][j] = -1; 38 } 39 printf("%-5d", plat[i][j]); 40 } 41 cout<<endl; 42 } 43 } 44 int main() { 45 scanf("%d%d%d%d",&n,&m,&sx,&sy); 46 bfs(sx, sy); 47 print(); 48 return 0; 49 }
十分朴素详实的bfs
感觉bfs全长一个样子QAQ