Skip to content

Instantly share code, notes, and snippets.

@maple3142
Created March 16, 2018 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maple3142/a09dae1635917df6e313db6a527a6cf1 to your computer and use it in GitHub Desktop.
Save maple3142/a09dae1635917df6e313db6a527a6cf1 to your computer and use it in GitHub Desktop.
【問題】螺旋矩陣(有非C語言的解法嗎 https://forum.gamer.com.tw/C.php?bsn=60076&snA=4453621
const n=3
function c2da(n,m){
const ar=[]
for(let i=0;i<n;i++)ar[i]=[]
return ar
}
const ar=c2da(n+1,n+1)
const vis=c2da(n+1,n+1)
const X=[1,0,-1,0]
const Y=[0,-1,0,1]
function dfs(x=1,y=1,c=1,d=3){
if(c>n*n)return
vis[x][y]=true
ar[x][y]=c
const xx=x+X[d],yy=y+Y[d]
if(xx<1||xx>n||yy<1||yy>n||vis[xx][yy])d=(d+1)%4
const xxx=x+X[d],yyy=y+Y[d]
dfs(xxx,yyy,c+1,d)
}
dfs()
for(let i=1;i<=n;i++){
console.log(ar[i].join(' '))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment