Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark mode
Gurobi Example Tour
Light LogoDark Logo
Gurobi
Back to top

sudoku.m#

functionsudoku(filename)%  Copyright 2025, Gurobi Optimization, LLC */%% Sudoku example.%% The Sudoku board is a 9x9 grid, which is further divided into a 3x3 grid% of 3x3 grids.  Each cell in the grid must take a value from 0 to 9.% No two grid cells in the same row, column, or 3x3 subgrid may take the% same value.%% In the MIP formulation, binary variables x[i,j,v] indicate whether% cell <i,j> takes value 'v'.  The constraints are as follows:%   1. Each cell must take exactly one value (sum_v x[i,j,v] = 1)%   2. Each value is used exactly once per row (sum_i x[i,j,v] = 1)%   3. Each value is used exactly once per column (sum_j x[i,j,v] = 1)%   4. Each value is used exactly once per 3x3 subgrid (sum_grid x[i,j,v] = 1)%% Input datasets for this example can be found in examples/data/sudoku*.%SUBDIM=3;DIM=SUBDIM*SUBDIM;fileID=fopen(filename);iffileID==-1fprintf('Could not read file %s, quit\n',filename);return;endboard=repmat(-1,DIM,DIM);fori=1:DIMs=fgets(fileID,100);iflength(s)<=DIMfprintf('Error: not enough board positions specified, quit\n');return;endforj=1:DIMifs(j)~='.'board(i,j)=str2double(s(j));ifboard(i,j)<1||board(i,j)>DIMfprintf('Error: Unexpected character in Input line %d, quit\n',i);return;endendendend% Map X(i,j,k) into an index variable in the modelnVars=DIM*DIM*DIM;% Build modelmodel.vtype=repmat('B',nVars,1);model.lb=zeros(nVars,1);model.ub=ones(nVars,1);fori=1:DIMforj=1:DIMforv=1:DIMvar=(i-1)*DIM*DIM+(j-1)*DIM+v;model.varnames{var}=sprintf('x[%d,%d,%d]',i,j,v);endendend% Create constraints:nRows=4*DIM*DIM;model.A=sparse(nRows,nVars);model.rhs=ones(nRows,1);model.sense=repmat('=',nRows,1);Row=1;% Each cell gets a value */fori=1:DIMforj=1:DIMforv=1:DIMifboard(i,j)==vmodel.lb((i-1)*DIM*DIM+(j-1)*DIM+v)=1;endmodel.A(Row,(i-1)*DIM*DIM+(j-1)*DIM+v)=1;endRow=Row+1;endend% Each value must appear once in each rowforv=1:DIMforj=1:DIMfori=1:DIMmodel.A(Row,(i-1)*DIM*DIM+(j-1)*DIM+v)=1;endRow=Row+1;endend% Each value must appear once in each columnforv=1:DIMfori=1:DIMforj=1:DIMmodel.A(Row,(i-1)*DIM*DIM+(j-1)*DIM+v)=1;endRow=Row+1;endend% Each value must appear once in each subgridforv=1:DIMforig=0:SUBDIM-1forjg=0:SUBDIM-1fori=ig*SUBDIM+1:(ig+1)*SUBDIMforj=jg*SUBDIM+1:(jg+1)*SUBDIMmodel.A(Row,(i-1)*DIM*DIM+(j-1)*DIM+v)=1;endendRow=Row+1;endendend% Save modelgurobi_write(model,'sudoku_m.lp');% Optimize modelparams.logfile='sudoku_m.log';result=gurobi(model,params);ifstrcmp(result.status,'OPTIMAL')fprintf('Solution:\n');fori=1:DIMforj=1:DIMforv=1:DIMvar=(i-1)*DIM*DIM+(j-1)*DIM+v;ifresult.x(var)>0.99fprintf('%d',v);endendendfprintf('\n');endelsefprintf('Problem was infeasible\n')end

Help and Feedback


[8]
ページ先頭

©2009-2025 Movatter.jp