https://www.luogu.com.cn/problem/P1443
C语言:
队列要自己写:
对齐:
printf("%-5d", -1);//左对齐
printf("%5d", -1);//右对齐
代码:
#include
#include
typedef struct
{
int x, y;
}Node;
typedef Node Qelemtype;
typedef struct
{
Qelemtype *base;
int front;
int rear;
}squeue;
const int MaxValue = 0x7fffffff, MaxSize = 160005;
int n, m;
int f[405][405], vis[405][405];
int fx[8][2]={{2, 1}, {2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}};
squeue q;
void InitQueue()
{
q.base = (Qelemtype *)malloc(MaxSize * sizeof(Qelemtype));
if (!q.base)
exit(-1);
q.front = 0;
q.rear = 0;
}
void PushQueue(Qelemtype x)
{
if (((q.rear + 1)%MaxSize) == q.front)
{
printf("¶ÓÂú\n");
exit(-1);
}
q.base[q.rear] = x;
q.rear = (q.rear + 1) % MaxSize;
}
Qelemtype PopQueue()
{
Qelemtype x;
if (q.front == q.rear)
{
printf("¶Ó¿Õ\n");
exit(-1);
}
x = q.base[q.front];
q.front = (q.front + 1) % MaxSize;
return x;
}
int EmptyQueue()
{
if (q.rear == q.front)
return 1;
else
return 0;
}
void bfs(int x, int y)
{
int i, x1, y1;
Node n1, n2;
while(!EmptyQueue())
{
n1 = PopQueue();
vis[n1.x][n1.y] = 0;
for (i = 0; i<8; i++)
{
x1 = n1.x + fx[i][0];
y1 = n1.y + fx[i][1];
if (x1 > n || x1 <= 0 || y1 > m || y1 <= 0)
continue;
if (f[x1][y1] > f[n1.x][n1.y] + 1 && vis[x1][y1] == 0)
{
n2.x = x1; n2.y = y1;
f[x1][y1] = f[n1.x][n1.y] + 1;
PushQueue(n2);
vis[x1][y1] = 1;
}
}
}
return ;
}
int main()
{
int i, x, y, j;
Node n1;
scanf("%d%d%d%d", &n, &m, &x, &y);
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
f[i][j] = MaxValue;
memset(vis, 0, sizeof(vis));
InitQueue();
f[x][y] = 0;
n1.x = x; n1.y = y;
PushQueue(n1);
vis[x][y] = 1;
bfs(x, y);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
if (f[i][j] == MaxValue)
printf("%-5d", -1);
else
printf("%-5d", f[i][j]);
}
printf("\n");
}
return 0;
}
python:
输入对齐:
print("|",format("Ursula","*>20"),"|") #左对齐
print("|",format("Ursula","*^20"),"|") #居中对齐
print("|",format("Ursula","*<20"),"|") #右对齐
全局变量:
只用在函数中加global即可
def f():
global x, y...
代码:
import queue
class Node(object):
def __init__(self):
self.x = None
self.y = None
def bfs():
global f, fx, q, vis, n, m
while not q.empty():
n1 = q.get()
vis[n1.x][n1.y] = 0
for i in range(8):
x1 = n1.x + fx[i][0]
y1 = n1.y + fx[i][1]
if x1 <= 0 or x1 > n or y1 <= 0 or y1 >m:
continue
if f[x1][y1] > f[n1.x][n1.y] + 1 and vis[x1][y1]==0:
f[x1][y1] = f[n1.x][n1.y] + 1
n2 = Node()
n2.x = x1
n2.y = y1
q.put(n2)
vis[x1][y1] = 1
s = input()
n0, m0, x0, y0 = s.split(' ')
n = eval(n0)
m = eval(m0)
x = eval(x0)
y = eval(y0)
MaxValue = 0x7fffffff
f = [[MaxValue for i in range(m + 5)] for j in range(n + 5)]
vis = [[0 for i in range(m + 5)] for j in range(n + 5)]
q = queue.Queue(n * m + 5)
fx = [[2, 1], [2, -1], [1, 2], [1, -2], [-1, 2], [-1, -2], [-2, 1], [-2, -1]]
vis[x][y] = 1
f[x][y] = 0
n1 = Node()
n1.x = x
n1.y = y
q.put(n1)
bfs()
for i in range(1, n+1):
for j in range(1, m+1):
if f[i][j] == MaxValue:
print(format(-1, " <5"), end='')
else:
print(format(f[i][j], " <5"), end='')
print(end='\n')