原方阵为S,输出方阵D,1元素对应的初始值设为0,0元素对应的初始值设为N*2。
遍历原矩阵,如果当前元素S[i,j]是1:
if i > 1 and D[i,j] + 1 < D[i-1,j] then
D[i-1,j] = D[i,j] + 1;
S[i-1,j] = 1;
end if
if i < N and D[i,j] + 1 < D[i+1,j] then
D[i+1,j] = D[i,j] + 1;
S[i+1,j] = 3;
end if
if j > 1 and D[i,j] + 1 < D[i,j-1] then
D[i,j-1] = D[i,j] + 1;
S[i,j-1] = 3;
end if
if j < N and D[i,j] + 1 < D[i,j+1] then
D[i,j+1] = D[i,j] + 1;
S[i,j+1] = 3;
end if
S[i,j] = 2;
把所有S中为3的元素设置为1。
重复上一步直到没有1元素。
如果在每次开始前先把所有的1元素位置读出来就不用把元素设为3了,可以直接设置为1。
如果用一个队列就更容易:
先把所有的1元素放到队列中;
while 队列非空 do
s[i,j]出队(从而得到i和j)
if i > 1 and D[i,j] + 1 < D[i-1,j] then
D[i-1,j] = D[i,j] + 1;
S[i-1,j] 入队;
end if
if i < N and D[i,j] + 1 < D[i+1,j] then
D[i+1,j] = D[i,j] + 1;
S[i+1,j] 入队;
end if
if j > 1 and D[i,j] + 1 < D[i,j-1] then
D[i,j-1] = D[i,j] + 1;
S[i,j-1] 入队;
end if
if j < N and D[i,j] + 1 < D[i,j+1] then
D[i,j+1] = D[i,j] + 1;
S[i,j+1]入队;
end if
end while