复制代码 代码如下: // <![CDATA[ <BR>var sudokuArray = [[],[],[],[],[],[],[],[],[],[]]; <BR>function onLoadTable() <BR>{ <BR>do <BR>{ <BR>sudokuArray = getNewArray(); <BR>sudokuArray = getSudokuArray(sudokuArray); <BR>} <BR>while(!checkArray(sudokuArray)) <BR>//document.getElementById("result").innerHTML=checkArray(sudokuArray); <BR>var table = document.getElementById("mainTable"); <BR>table.removeChild(table.firstChild); <BR>for(var i=0;i<9;i++) <BR>{ <BR>table.insertRow(i); <BR>for(var j=0;j<9;j++) <BR>{ <BR> table.rows[i].insertCell(j); <BR> table.rows[i].cells[j].innerHTML = sudokuArray[i][j];//Math.round(Math.random()*8+1); <BR>setStyle(i,j,table.rows[i].cells[j]); <BR>} <BR>} <BR>} <BR>function getSudokuArray(filledArray) <BR>{ <BR>var failed = false; <BR>for(var i=0;i<9;i++) <BR>{ <BR> for(var j=0;j<9;j++) <BR> { <BR> var tempArray = getAvaildableArray(i, j, filledArray); <BR> if(tempArray.length > 0) <BR> { <BR> filledArray[i][j] = tempArray[Math.round(Math.random()*(tempArray.length-1))]; <BR> } <BR> else <BR> { <BR> //window.location.reload(); <BR> } <BR> } <BR> } <BR> return filledArray; <BR>} <BR>function checkArray(array) <BR>{ <BR>for(var i=0;i<9;i++) <BR>{ <BR> for(var j=0;j<9;j++) <BR> { <BR> if(array[i][j] == undefined) <BR> { <BR> return false; <BR> } <BR> } <BR>} <BR>return true; <BR>} <BR>function getAvaildableArray(rowIndex, cellIndex, array) <BR>{ <BR>var availdableArray = [1,2,3,4,5,6,7,8,9]; <BR>for(var n=0;n<9;n++) <BR>{ <BR>if(!isNaN(array[rowIndex][n]) && array[rowIndex][n] != undefined) <BR>{ <BR>availdableArray[array[rowIndex][n]-1] = NaN; <BR>} <BR>if(!isNaN(array[n][cellIndex]) && array[n][cellIndex] != undefined) <BR>{ <BR>availdableArray[array[n][cellIndex]-1] = NaN; <BR>} <BR>} <BR>var rowStartIndex = Math.floor(rowIndex/3); <BR>var cellStartIndex = Math.floor(cellIndex/3); <BR>for(var x=rowStartIndex*3;x<rowStartIndex+3;x++) <BR>{ <BR>for(var y=cellStartIndex*3;y<cellStartIndex+3;y++) <BR>{ <BR>if(!isNaN(array[x][y]) || array[x][y] != undefined) <BR>{ <BR>availdableArray[array[x][y]-1] = NaN; <BR>} <BR>} <BR>} <BR>var returnArray = []; <BR>for(var m=0;m<9;m++) <BR>{ <BR>if(!isNaN(availdableArray[m])) <BR>{ <BR>returnArray.push(availdableArray[m]); <BR>} <BR>} <BR>return returnArray; <BR>} <BR>function getNewArray() <BR>{ <BR>return [[],[],[],[],[],[],[],[],[],[]]; <BR>} <BR>function setStyle(rowIndex,cellIndex,cell) <BR>{ <BR>cell.height="20"; <BR>cell.width="20"; <BR>if(cellIndex%3==2) <BR>{ <BR> cell.style.borderRightColor="red"; <BR>} <BR>if(cellIndex%3==0) <BR>{ <BR> cell.style.borderLeftColor="red"; <BR>} <BR>if(rowIndex%3==2) <BR>{ <BR> cell.style.borderBottomColor="red"; <BR>} <BR>if(rowIndex%3==0) <BR>{ <BR> cell.style.borderTopColor="red"; <BR>} <BR>} <BR>// ]]>