dfs--二维数组没有办法存储,只有用一维数组模拟

 1 Seating of Students
 2  2000ms  262144K
 3 描述:
 4 Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."
 5 
 6 The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.
 7 
 8 Let's enumerate students from 1 to n·m in order of rows. So a student who initially sits in the cell in row i and column j has a number (i - 1)·m + j. You have to find a matrix with n rows and m columns in which all numbers from 1 to n·m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.
 9 
10 输入:
11 The only line contains two integers n and m (1 ≤ n, m ≤ 105; n·m ≤ 105) — the number of rows and the number of columns in the required matrix.
12 
13 输出:
14 If there is no such matrix, output "NO" (without quotes).
15 
16 Otherwise in the first line output "YES" (without quotes), and in the next n lines output m integers which form the required matrix.
17 
18 样例输入:
19 2 4
20 样例输出:
21 YES
22 5 4 7 2 
23 3 6 1 8 
24 样例输入:
25 2 1
26 样例输出:
27 NO
28 注释:
29 In the first test case the matrix initially looks like this:
30 
31 
32 1 2 3 4
33 5 6 7 8
34 It's easy to see that there are no two students that are adjacent in both matrices.
35 
36 In the second test case there are only two possible seatings and in both of them students with numbers 1 and 2 are neighbors.

我们能够很清楚看到,n<10^5,m<10^5,n*m<10^5,

如果我们开数组arr[10^5][10^5],毫无疑问会爆(二维数组最多大概开arr[900][900]),只有用一维数组,

如这个大佬所写:

 

思路:根据题目所给的数据范围我们知道肯定不能用二维数组储存数字然后dfs搜索遍历,而是直接进行模拟遍历,题目给了一个公式(i - 1)·m + j。也就是如果我们知道了矩阵中的位置(i,j)那这个位置原始数字应该是(i-1)*m+j,那么反过来如果我们知道了一个数字如果得到这个数字的原始在矩阵中的位置呢如果已知数字大小是i那么这个数字在矩阵的初始位置x = (i-1)/m+1
————————————————
版权声明:本文为CSDN博主「Guuuuuu老师儿」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/codeswarrior/article/details/79955965

注意:代码实现的巧妙

 

posted @ 2022-05-02 10:12  次林梦叶  阅读(35)  评论(0)    收藏  举报