用js写的螺旋矩阵算法,很有意思
<html>
<head>
<style>
.a{ text-align:right; background-color:#CCFFCC; font:16pt ‘verdana’}
</style>
<script language="JScript">
<!–
var DGrid=new Array(8);
function InitGrid(){
for(var i=0;i<8;i++){
DGrid[i]=new Array(8);
for(var j=0; j<8;j++){
DGrid[i][j]=0;
}
}
}
function InitDigit(){
var X = 3;
var Y = 3;
var N = 2;
var dir=0;
var t=0;
DGrid[3][3]=1;
for(var i=0;i<7;i++){
for(var j=1;j<=2;j++){
t=0;
while(t<=i){
X+=(dir==0)?1:((dir==2)?-1:0);
Y+=(dir==1)?1:((dir==3)?-1:0);
DGrid[X][Y]=N;
N++;t++;
}
dir ++;
dir %= 4;
}
}
}
function ShowGrid(obj,n){
//alert(n);
if(n<0 || n>7){
return;
}else{
alert("超出范围!");
}
InitGrid();
InitDigit();
str="<Table border=1 align=center>";
var v1 = Math.ceil(3-n/2.0+0.5);
var v2 = v1 + n ;
for(var i=v1;i<v2;i++){
str+="<Tr>";
for(var j=v1;j<v2;j++)
str+="<TD class=’a’onmouseover=’over(this)’ onmouseout=’out(this)’> "+DGrid[j][i]+" </TD>";
str+="</Tr>"
}
str +="</Table>";
obj.innerHTML=str;
}
function over(obj){
obj.style.backgroundColor="#FFCCCC";
}
function out(obj){
obj.style.backgroundColor="#CCFFCC";
}
–>
</script>
</head>
<body >
<Form>
<Input id="NGrid" value="7"></Input>
<Button onclick="ShowGrid(grid,parseInt(NGrid.value));">开始</Button>
</Form>
<br>
<div id="grid">
<div>
</body>
</html>