关于return的理解

来源:互联网 发布:淘宝我的购物车打不开 编辑:程序博客网 时间:2024/06/06 02:53
Sudoku
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 21134 Accepted: 10076 Special Judge

Description

Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task. 

Input

The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.

Output

For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.

Sample Input

1103000509002109400000704000300502006060000050700803004000401000009205800804000107

Sample Output

143628579572139468986754231391542786468917352725863914237481695619275843

854396127

这道题有一个关于return的地方,就是DFS到某一个阶段的时候,如果函数没有返回值,那么DFS也就停止了。这道题由于我理解

题意产生了错误,导致return的使用出现了很大的问题。以下三个版本都是关这个错误的解释。

void dfs(int idx)  {          if(idx<0){flag=1;return;  }      for(int i=1;i<=9;i++)      {          int x=vis[idx][0];          int y=vis[idx][1];          if(judge(x,y,i))          {              g[x][y]=i;              dfs(idx-1);            if(flag) return ;            g[x][y]=0;          }      }      return ;  }  
这个是用flag直接退出DFS函数。
int dfs(int idx)  {      if(idx<0)return 1;      for(int i=1;i<=9;i++)      {          int x=vis[idx][0];          int y=vis[idx][1];          if(judge(x,y,i))          {              g[x][y]=i;              if(dfs(idx-1))return 1;              g[x][y]=0;          }      }      return 0;  }  

这个是用返回值的方法退出DFS函数,跟用FLAG一个性质。但这个做法对于深刻理解return的用处以及含义是非常有用处的。

void dfs(int idx)  {          if(idx<0){return;  }      for(int i=1;i<=9;i++)      {          int x=vis[idx][0];          int y=vis[idx][1];          if(judge(x,y,i))          {              g[x][y]=i;              dfs(idx-1);            if(idx<0) return;            g[x][y]=0;          }      }      return ;  }  
这个代码就是错误的,因为这个代码会输出很多不对的情况,DFS会反复执行很多遍。
void dfs(int idx)  {          if(idx<0){  }      for(int i=1;i<=9;i++)      {          int x=vis[idx][0];          int y=vis[idx][1];          if(judge(x,y,i))          {              g[x][y]=i;              dfs(idx-1);            if(idx<0) return;            g[x][y]=0;          }      }   } 
这个代码一旦出现idx<0的情况,DFS函数就执行结束。




 
原创粉丝点击